Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 39534 | Accepted: 18565 | |
Case Time Limit: 2000MS |
Description
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.
Input
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 30
题意:给你一个N个数的序列,有M次查询,查询区间[x, y]的最大值与最小值之差。
AC代码:
#include <cstdio> #include <cstring> #include <algorithm> #define MAXN 50000+10 using namespace std; int A[MAXN]; int Amax[MAXN][30]; int Amin[MAXN][20]; int N, M; void RMQ_init() { for(int i = 1; i <= N; i++) Amax[i][0] = Amin[i][0] = A[i]; for(int j = 1; (1<<j) <= N; j++) { for(int i = 1; i + (1<<j) - 1 <= N; i++) { Amax[i][j] = max(Amax[i][j-1], Amax[i + (1<<(j-1))][j-1]); Amin[i][j] = min(Amin[i][j-1], Amin[i + (1<<(j-1))][j-1]); } } } int query(int L, int R) { int k = 0; while((1 << (k+1)) <= R-L+1) k++; return max(Amax[L][k], Amax[R - (1<<k) + 1][k]) - min(Amin[L][k], Amin[R - (1<<k) + 1][k]); } int main() { while(scanf("%d%d", &N, &M) != EOF) { for(int i = 1; i <= N; i++) scanf("%d", &A[i]); RMQ_init(); int x, y; while(M--) { scanf("%d%d", &x, &y); printf("%d\n", query(x, y)); } } return 0; }