zoukankan      html  css  js  c++  java
  • poj p3264——Balanced Lineup(RMQ)

    Description

    For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

    Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

    Input

    Line 1: Two space-separated integers, N and Q
    Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i 
    Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

    Output

    Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

    Sample Input

    6 3
    1
    7
    3
    4
    2
    5
    1 5
    4 6
    2 2

    Sample Output

    6
    3
    0


    因为只用查找不用更新,所以可以用RMQ算法。(RMQ算法详解见随笔)

    #include<cstdio>
    #include<iostream>
    #include<cmath>
    using namespace std;
    int m,n;
    int a[100005];
    int maxx[100005][25];
    int minx[100005][25];int ans1,ans2;
    int main()
    {
      scanf("%d%d",&m,&n);//cin>>m>>n;
      for(int i=1;i<=m;i++)
      {
        scanf("%d",&maxx[i][0]);//cin>>maxx[i][0];
        minx[i][0]=maxx[i][0];
      }

      for(int j=1;j<=20;j++)
      for(int i=1;i<=m;i++)
      if(i+(1<<j)-1<=m)
      {
        maxx[i][j]=max(maxx[i][j-1],maxx[i+((1<<j-1))][j-1]);
        minx[i][j]=min(minx[i][j-1],minx[i+((1<<j-1))][j-1]);
      }
      for(int i=1;i<=n;i++)
      {
        int x,y;
        scanf("%d%d",&x,&y);//cin>>x>>y;
        int k=(int)(log(y-x+1)/log(2.0));
        ans1=max(maxx[x][k],maxx[y-(1<<k)+1][k]);
        ans2=min(minx[x][k],minx[y-(1<<k)+1][k]);
        cout<<ans1-ans2<<endl;
      }
      return 0;
    }

     
  • 相关阅读:
    上周热点回顾(12.2112.27)
    评论表聚集索引引起的评论超时问题
    上周热点回顾(11.3012.6)
    jQuery 专题上线了
    博客园电子期刊2009年11月刊发布啦
    memcached罢工引发的血案博客园评论超时问题处理过程
    机房线路割接通知
    上周热点回顾(12.712.13)
    博客园首页优化心得
    上周热点回顾(12.1412.20)
  • 原文地址:https://www.cnblogs.com/937337156Zhang/p/5667961.html
Copyright © 2011-2022 走看看