poj3264 Balanced Lineup(RMQ +st)

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<map>
#include<queue>
#include <deque>
#include <list>
#include <ctime>
#include <stack>
#include <vector>
#include<set>
#define Maxn 50005
#define MOD
typedef long long ll;
#define FOR(i,j,n) for(int i=j;i<=n;i++)
#define DFR(i,j,k) for(int i=j;i>=k;--i)
#define lowbit(a) a&-a
const int inf = 0x3f3f3f3f;
const double pi = acos(-1.0);
const double e=2.7182818284590452354;
using namespace std;
int num[Maxn];
int f1[Maxn][100];
int f2[Maxn][100];
void st(int n)
{
    int i,j,k,m;
    k=(int)(log((double)n)/log(2.0));
    for(i=0;i<n;i++)
    {
        f1[i][0]=num[i];
        f2[i][0]=num[i];
    }
    for(j=1;j<=k;j++)
    {
        for(i=0;i+(1<<j)-1<n;i++)
        {
            m = i + (1<<(j-1));
            f1[i][j]=max(f1[i][j-1],f1[m][j-1]);
            f2[i][j]=min(f2[i][j-1],f2[m][j-1]);
        }
    }
}
void rmq(int i,int j)
{   int k = (int)(log(double(j-i+1))/log(2.0)),t1,t2;
    t1 = max(f1[i][k],f1[j-(1<<k)+1][k]);
    t2 = min(f2[i][k],f2[j-(1<<k)+1][k]);
    printf("%d\n",t1-t2);

}
int main()
{   int n, query;
    int a, b;
    while(~scanf("%d %d", &n, &query))
    {
        FOR(i,0,n-1)scanf("%d", num+i);
        st(n);
        while(query--)
        {
            scanf("%d%d", &a, &b);
            rmq(a-1,b-1);

        }
    }
    return 0;
}






你可能感兴趣的:(RMQ,st)