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;
    }

     
  • 相关阅读:
    007_在线解析json工具
    009_python魔法函数
    008_python列表的传值与传址
    008_python内置语法
    007_Python中的__init__,__call__,__new__
    006_Python 异常处理
    匹配网络设计
    Bessel函数
    system generator 卷积编码器快速设计
    关于非稳恒的电流激励电场
  • 原文地址:https://www.cnblogs.com/937337156Zhang/p/5667961.html
Copyright © 2011-2022 走看看