tzoj1698: Balanced Lineup(區間最值,rmq演算法)
描述
For the daily milking, Farmer John'sNcows (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 ofQ(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,NandQ.
Lines 2..N
LinesN+2..N+Q+1: Two integersAandB(1 ≤A≤B≤N), representing the range of cows fromAtoBinclusive.
輸出
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; }程式碼