【清北前紧急补课1】rmq

 

poj3264 balanced lineup

题目描述

For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

输入输出格式

输入格式:

 

Line 1: Two space-separated integers, N and Q.

Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i

Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

 

输出格式:

 

Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

 

 

主要还是要用rmq(虽然有人告诉我用贪心模拟可我觉得一定会爆

 

rmq就是在一个区间里找最小值或最大值 用st的做法

理解一下rmq的原理:假设我们要查询的这个数值在区间a[i]中,那么我们用f[i][j]来表示这个数;具体含义是这样的:f[i][j]表示 从i开始的2^j个数中的最大值 那么就可以确定a[i]=f[i][0];

那么对于一个2^j的数列我们可以把他平均分成两段 每段的长度为2^j-1;第一段是i到i+2^j-1 -1;第二段是i+2^j-1到i+2^j-1;

可以分别表示为:f[i][j-1]  f[i+2^j-1][j-1]

则设有2^k=j-i+1(即一个从i到j的区间的长度)那么有rmq(i,j)=max(f[i][k],f[j-2^k+1][k]);(区间最大值 最小值同理

 

则可以得出这个题的程序:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int n,q,s,e,maxn,minn;
int f1[200001][51],f2[200001][51],a[200001];

int rmq(int i,int j){
    int k=0;
    while((1<<(k+1))+i<=j+1) k++;
    minn=min(f2[i][k],f2[j-(1<<k)+1][k]);
    maxn=max(f1[i][k],f1[j-(1<<k)+1][k]);
    return maxn-minn;
}

int main(){
    scanf("%d%d",&n,&q);
    for(int i=1;i<=n;i++) cin>>a[i];
    for(int i=1;i<=n;i++){
        f1[i][0]=f2[i][0]=a[i];
    }
    for(int j=1;(1<<j)<=n;j++)
    for(int i=1;i+(1<<j)<=n+1;i++){
        f1[i][j]=max(f1[i][j-1],f1[(1<<(j-1))+i][j-1]);
        f2[i][j]=min(f2[i][j-1],f2[(1<<(j-1))+i][j-1]);
    }
    for(int i=1;i<=q;i++){
        scanf("%d%d",&s,&e);
        cout<<rmq(s,e)<<endl;
    } 
    return 0;
}

岂不nice

 

关于st表的k的另一种求法

for (int a=1;(1<<a)<=n;a++)
        er[(1<<a)]=a;
    for (int a=3;a<=n;a++)
        if (er[a]==0) er[a]=er[a-1];

 

再另建一个函数

int query(int l,int r)
{
    int k=er[r-l+1];
    return max(f[l][k],f[r-(1<<k)+1][k]);
}

 

posted @ 2018-07-16 16:59  东方的古文明  阅读(96)  评论(0编辑  收藏  举报