poj 3264 RMQ

直接写个RMQ就能过。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define Max(a,b) ((a)>(b)?(a):(b))
#define Min(a,b) ((a)<(b)?(a):(b))
#define Maxn 60010
using namespace std;
int maxnum[Maxn][20],minnum[Maxn][20],n,Log[Maxn+10];
int Log2(int x)
{
    int num=0;
    x/=2;
    while(x)
    {
        num++;
        x/=2;
    }
    return num;
}
void RMQ()
{
    int i,j;
    for(j=1;j<20;j++)
        for(i=1;i<=n;i++)
        if(i+(1<<j)-1<=n)
        {
            maxnum[i][j]=Max(maxnum[i][j-1],maxnum[i+(1<<(j-1))][j-1]);
            minnum[i][j]=Min(minnum[i][j-1],minnum[i+(1<<(j-1))][j-1]);
        }
}
int main()
{
    int i,j,q,a,b;
    for(i=1;i<=60010;i++)
        Log[i]=Log2(i);
    while(scanf("%d%d",&n,&q)!=EOF)
    {

        for(i=1;i<=n;i++)
        {
            scanf("%d",&a);
            maxnum[i][0]=minnum[i][0]=a;
        }
        RMQ();
        for(i=1;i<=q;i++)
        {
            scanf("%d%d",&a,&b);
            int k=Log[b-a+1];
            printf("%d\n",Max(maxnum[a][k],maxnum[b-(1<<k)+1][k])-Min(minnum[a][k],minnum[b-(1<<k)+1][k]));
        }
    }
    return 0;
}

 

posted @ 2013-07-29 20:14  fangguo  阅读(194)  评论(0编辑  收藏  举报