RMQ模板

附上一个详细的大佬的讲解  http://blog.csdn.net/niushuai666/article/details/6624672

 

RMQ模板(NYOJ 119)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXN=1e5+10;
int a[MAXN];
int maxsum[MAXN][20];
int minsum[MAXN][20];
int maxx;
int minn;
void RMQ_In(int num) //预处理->O(nlogn)
{
    for(int j = 1; j < 20; ++j)
        for(int i = 1; i <= num; ++i)
            if(i + (1 << j) - 1 <= num)
            {
                maxsum[i][j] = max(maxsum[i][j - 1], maxsum[i + (1 << (j - 1))][j - 1]);
                minsum[i][j] = min(minsum[i][j - 1], minsum[i + (1 << (j - 1))][j - 1]);
            }
}
void RMQ_Query(int src,int des)
{
if(src>des)
        swap(src,des);
int k=(int)(log(des-src+1.0)/log(2.0)); maxx=max(maxsum[src][k],maxsum[des-(1<<k)+1][k]); minn=min(minsum[src][k],minsum[des-(1<<k)+1][k]); } int main() { int n,q,a,b; scanf("%d%d",&n,&q); for(int i=1;i<=n;i++){ scanf("%d",&minsum[i][0]); maxsum[i][0]=minsum[i][0]; } RMQ_In(n); while(q--) { scanf("%d%d",&a,&b); RMQ_Query(a,b); printf("%d\n",maxx-minn); } return 0; }

 

posted @ 2017-08-22 21:17  hinata_hajime  阅读(213)  评论(0编辑  收藏  举报