Balanced Lineup(POJ-3264)
Problem 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
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.
Output
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.
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
思路:與?平衡的陣容(洛谷-P2880)同一題
Source Program
#include<iostream> #include<cstdio> #include<cstdlib> #include<string> #include<cstring> #include<cmath> #include<ctime> #include<algorithm> #include<utility> #include<stack> #include<queue> #include<vector> #include<set> #include<map> #include<bitset> #define EPS 1e-9 #define PI acos(-1.0) #define INF 0x3f3f3f3f #define LL long long #define Pair pair<int,int>const int MOD = 1E9+7; const int N = 1000000+5; const int dx[] = {-1,1,0,0,-1,-1,1,1}; const int dy[] = {0,0,-1,1,-1,1,-1,1}; using namespace std;int dpMax[N][20]; int dpMin[N][20]; int a[N]; void initMax(int n){//初始化最大值查詢for(int i=1;i<=n;i++)dpMax[i][0]=a[i];for(int j=1;(1<<j)<=n;j++)for(int i=1;i+(1<<j)-1<=n;i++)dpMax[i][j]=max(dpMax[i][j-1],dpMax[i+(1<<(j-1))][j-1]); } int getMax(int L,int R){//查詢最大值//int k = (int)(log10(R-L+1)/log10(2));int k=0;while((1<<(k+1))<=R-L+1)k++;return max(dpMax[L][k],dpMax[R-(1<<k)+1][k]); }void initMin(int n){//初始化最小值查詢for(int i=1;i<=n;i++)dpMin[i][0]=a[i];for(int j=1;(1<<j)<=n;j++)for(int i=1;i+(1<<j)-1<=n;i++)dpMin[i][j]=min(dpMin[i][j-1],dpMin[i+(1<<(j-1))][j-1]); } int getMin(int L,int R){//查詢最小值//int k = (int)(log10(R-L+1)/log10(2));int k=0;while((1<<(k+1))<=R-L+1)k++;return min(dpMin[L][k],dpMin[R-(1<<k)+1][k]); } int main(){int n,m;scanf("%d%d",&n,&m);for(int i=1;i<=n;i++)scanf("%d",&a[i]);initMax(n);initMin(n);for(int i=1;i<=m;i++){int left,right;scanf("%d%d",&left,&right);int maxx=getMax(left,right);int minn=getMin(left,right);printf("%d\n",maxx-minn);}return 0; }?
總結
以上是生活随笔為你收集整理的Balanced Lineup(POJ-3264)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 加工生产调度(信息学奥赛一本通-T142
- 下一篇: 图论 —— 支配树