| Time Limit: 5000MS | Memory Limit: 65536K | |
| Total Submissions: 64964 | Accepted: 30260 | |
| 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
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.
Output
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
Source
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cstring> #include <cmath> #include <stack> #include <vector> #include <queue> #include <map> #include <set> #include <climits> #include <cassert> #define min(a,b) ((a)<(b)?(a):(b)) #define max(a,b) ((a)>(b)?(a):(b)) #define LL long long #define MAXX 50000+10 using namespace std; int maxx[MAXX][32],minn[MAXX][32]; int n,m; int main(){ while(~scanf("%d %d",&n,&m)){ fill(maxx[0],maxx[0]+MAXX*32,0); fill(minn[0],minn[0]+MAXX*32,0); for(int i=1;i<=n;i++){ scanf("%d",&minn[i][0]); maxx[i][0] =minn[i][0]; } int z=log(n*1.0)/log(2.0); for(int j=1;j<=z;j++){ for(int i=1;i<=n;i++){ if(n<(i+(1<<(j-1))) ) break; maxx[i][j]=max(maxx[i][j-1],maxx[i+(1<<(j-1))][j-1]); minn[i][j]=min(minn[i][j-1],minn[i+(1<<(j-1))][j-1]); } } int x,y,sum; for(int i=1;i<=m;i++){ scanf("%d%d", &x, &y); int k = log(y - x + 1.0) / log(2.0); //int minnn=min(minn[x][k], minn[y - (1<<k) + 1][k]); sum=(max(maxx[x][k], maxx[y - (1<<k) + 1][k]) - min(minn[x][k], minn[y - (1<<k) + 1][k])); //printf("%d\n",minnn); printf("%d\n", sum); } } }
本文介绍了一种解决区间最大最小值查询问题的有效算法,通过预处理数据建立稀疏表,实现快速查询任意区间内的最大值和最小值,适用于大量查询场景。
336

被折叠的 条评论
为什么被折叠?



