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

     
  • 相关阅读:
    [转]VS 2008 新特性一览
    [转]WCF开发框架形成之旅WCF的几种寄宿方式
    [转]失业的程序员(五):商战之前
    [ 转]Android折叠列表 ExpandableList
    [转]extjs入门——开始
    [转]Jquery操作select
    Ext JS 下载 及 是否收费
    [转]WCF服务的批量寄宿
    [转]Android高手进阶教程(十七)之Android中Intent传递对象的两种方法(Serializable,Parcelable)!
    mat之三PermGen Metaspace永久代内存分析
  • 原文地址:https://www.cnblogs.com/937337156Zhang/p/5667961.html
Copyright © 2011-2022 走看看