POJ 3264 RMQ

RMQ的模板题吧。。

/*
ID: liven052
LANG: C++
TASK: test
*/
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

typedef  long long LL;
const double PI = acos(-1.0);

template <class T> inline  T MAX(T a, T b){if (a > b) return a;return b;}
template <class T> inline  T MIN(T a, T b){if (a < b) return a;return b;}

const int N = 111;
const int M = 11111;
const LL MOD = 1000000007LL;
const int dir[4][2] = {1, 0, -1, 0, 0, -1, 0, 1};
const int INF = 0x3f3f3f3f;


int mi[50500][50], ma[50500][50], w[50500];
int n, q;

void rmqinit()
{
    int lim, i, j;
    for (i = 1; i <= n; ++i) mi[i][0] = ma[i][0] = w[i];
    lim = log((double)(n + 1))/ log(2.0);
    for (j = 1; j <= lim; ++j)
        for (i = 1; i + (1 << j) - 1 <= n; ++i)
        {
            mi[i][j] = MIN(mi[i][j - 1], mi[i + (1 <<(j - 1))][j - 1]);
            ma[i][j] = MAX(ma[i][j - 1], ma[i + (1 <<(j - 1))][j - 1]);
        }
}

int check(int a, int b)
{
    int k = (int)(log((double)(b - a + 1))/ log(2.0));
    return MAX(ma[a][k], ma[b-(1<<k)+1][k]) - MIN(mi[a][k], mi[b-(1<<k)+1][k]);
}


int main()
{
    while (scanf("%d%d", &n, &q) != EOF)
    {
        for (int i = 1; i <= n; ++i)
            scanf("%d", &w[i]);
        rmqinit();
        int a, b;
        for (int i = 0; i < q; ++i)
        {
            scanf("%d%d", &a, &b);
            printf("%d\n", check(a,b));
        }
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值