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

     
  • 相关阅读:
    蓝牙搜索
    Log4cpp介绍及使用
    单独卸载vs2010帮助文档HelpView之后的独立安装教程
    C++Builder RAD Studio XE, UTF-8 String 转换为 char * 字符串的最简单方式, 常用于sqlite3开发
    vs2012 MSDN帮助文档离线包下载安装方法
    关于OBJ/LIB格式,我以前有个总结
    关于C++ const 的全面总结
    在 C++Builder 工程里调用 DLL 函数
    c++builder调用VC的dll以及VC调用c++builder的dll
    C++Builder及VC的库相互调用
  • 原文地址:https://www.cnblogs.com/937337156Zhang/p/5667961.html
Copyright © 2011-2022 走看看