tzoj1698: Balanced Lineup(区间最值,rmq算法)
作者:互联网
描述
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算法
#include<bits/stdc++.h> using namespace std; const int MAXN = 50010; int dp1[MAXN][20],dp2[MAXN][20]; int mm1[MAXN],mm2[MAXN]; void initRMQmax(int n,int b[]){ mm1[0] = -1; for(int i = 1; i <= n;i++){ mm1[i] = ((i&(i-1)) == 0)?mm1[i-1]+1:mm1[i-1]; dp1[i][0] = b[i]; } for(int j = 1; j <= mm1[n];j++) for(int i = 1;i + (1<<j) -1 <= n;i++) dp1[i][j] = max(dp1[i][j-1],dp1[i+(1<<(j-1))][j-1]); } void initRMQmin(int n,int b[]){ mm2[0] = -1; for(int i = 1; i <= n;i++){ mm2[i] = ((i&(i-1)) == 0)?mm2[i-1]+1:mm2[i-1]; dp2[i][0] = b[i]; } for(int j = 1; j <= mm2[n];j++) for(int i = 1;i + (1<<j) -1 <= n;i++) dp2[i][j] = min(dp2[i][j-1],dp2[i+(1<<(j-1))][j-1]); } int rmqmax(int x,int y){ int k = mm1[y-x+1]; return max(dp1[x][k],dp1[y-(1<<k)+1][k]); } int rmqmin(int x,int y){ int k = mm2[y-x+1]; return min(dp2[x][k],dp2[y-(1<<k)+1][k]); } int main() { int n,q; int b[MAXN]; scanf("%d%d",&n,&q); for(int i=1;i<=n;i++) scanf("%d",&b[i]); initRMQmax(n,b); initRMQmin(n,b); int l,r; while(q--) { scanf("%d%d",&l,&r); printf("%d\n",rmqmax(l,r)-rmqmin(l,r)); } return 0; }代码
标签:rmq,int,height,cows,000,MAXN,Farmer,Balanced,tzoj1698 来源: https://www.cnblogs.com/zenghuan0620/p/13324264.html