您的位置:首页 > 其它

poj_3264 Balanced Lineup(RMQ)

2017-01-16 19:48 387 查看
Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536K
Total Submissions: 50087 Accepted: 23464
Case Time Limit: 2000MS
DescriptionFor 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 rangeof 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.InputLine 1: Two space-separated integers, N andQ.Lines 2..N+1: Line i+1 contains a single integer that is the height of cowiLines N+2..N+Q+1: Two integers A and B (1 ≤A ≤ B ≤ N), representing the range of cows from A toB inclusive.OutputLines 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.Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
RMQ模板题,求出区间最小值最大值,作差就好。
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <stack>#include <bitset>#include <queue>#include <set>#include <map>#include <string>#include <algorithm>#define FOP freopen("data.txt","r",stdin)#define FOP2 freopen("data1.txt","w",stdout)#define inf 0x3f3f3f3f#define maxn 50010#define mod 1000000007#define PI acos(-1.0)#define LL long longusing namespace std;int n, m;int a[maxn];int d_min[maxn][32], d_max[maxn][32];void RMQ_init(){for(int i = 0; i < n; i++) d_min[i][0] = d_max[i][0] = a[i];for(int j = 1; (1<<j) <= n; j++){for(int i = 0; i+(1<<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(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]) - min(d_min[L][k], d_min[R-(1<<k)+1][k]);}int main(){while(~scanf("%d%d", &n, &m)){for(int i = 0; i < n; i++) scanf("%d", &a[i]);RMQ_init();int l, r;while(m--){scanf("%d%d", &l, &r);printf("%d\n", RMQ(l-1, r-1));}}return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: