RMQ算法

来源:互联网 发布:linux中cat命令详解 编辑:程序博客网 时间:2024/04/28 00:06

http://blog.csdn.net/liang5630/article/details/7917702

1巴蜀oj1939

Description
  现给你n(<=1000000)个整数(都小于longint),有k(0< k<= 1000000)个询问,对于每个询问(L,R),回答(L,R)内的最大值为多少?
Input
  第一行两个整数n和k;第二行为n个整数,第三行到第k+2行为k个询问;
Output
  共k行,每行为一个询问的最大值
Sample Input
  10 2
  3 2 4 5 6 8 1 2 9 7
  1 8
  2 9
Sample Output
8
 9

#include<iostream>#include<cmath>#include<algorithm>using namespace std;int a[20001],f[1000][100];int main(){  int n,k;   cin>>n>>k;   for (int i=1;i<=n;++i)   {  int x;      cin>>x;      f[i][0]=x;   }   for (int j=1;(1<<j)<=n;++j)     for (int i=1;i+(1<<j)-1<=n;++i)       f[i][j]=max(f[i][j-1],f[i+(1<<j-1)][j-1]);   for (int l=1;l<=k;++l)   {  int x,y;cin>>x>>y;      int lg=log(y-x+1)/log(2);      int ans=max(f[x][lg],f[y-(1<<lg)+1][lg]);      cout<<ans<<endl;   }}  
2 0