RMQ模板题 poj3264 Balanced Lineup


poj3264 ST算法模板题

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 80000;
const int maxm = 30;
int d_min[maxn][maxm],d_max[maxn][maxm],a[maxn];
int n;
void RMQ_init(){
    int i,j;
    for(i = 1; i <= n; i++){
        d_min[i][0] = a[i];
        d_max[i][0] = a[i];
    }
    for(j = 1; (1<<j) <= n; j++)
    for(i = 1; i + j - 1 <= n; i++){
        d_min[i][j] = min(d_min[i][j-1],d_min[i + (1<<(j-1))][j-1]);
        d_max[i][j] = max(d_max[i][j-1],d_max[i + (1<<(j-1))][j-1]);
    }
}

int RMQ_min(int l,int r){
    int k = 0;
    while((1<<(k+1)) <= r-l+1)
        k++;
    return min(d_min[l][k], d_min[r-(1<<k)+1][k]);
}
int RMQ_max(int l,int r){
    int k = 0;
    while((1<<(k+1)) <= r-l+1)
        k++;
    return max(d_max[l][k], d_max[r-(1<<k)+1][k]);
}
int main()
{
    int q,l,r,i;
    scanf("%d%d",&n,&q);
    for(i = 1; i <= n; i++)
    scanf("%d",&a[i]);
    RMQ_init();
    while(q--){
        scanf("%d%d",&l,&r);
        printf("%d\n",RMQ_max(l,r)-RMQ_min(l,r));
    }
    return 0;
}
posted @ 2017-11-22 21:13  神探小小狄  阅读(63)  评论(0编辑  收藏  举报
【推荐】 程序员网址大全  |  EF CodeFirst  |  百度地图.NET  |  MyNPOI  |  开源  |  我的皮肤  |  ASP.NET MVC4  |  前端提升   |  LINQ   |  WCF   |  EasyUI  | aaronyang 页脚html代码