[USACO07JAN]平衡的阵容Balanced Lineup
题目描述
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.
一个农夫有N头牛,每头牛的高度不同,我们需要找出最高的牛和最低的牛的高度差。
输入输出格式
输入格式:
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.
输入输出样例
6 3 1 7 3 4 2 5 1 5 4 6 2 2
6 3 0
题解:
一道裸的倍增,维护两个数组保存最大值和最小值,注意查找的时候实际上只需要查找两次就可以了。
然后用最大值和最小值做一下差即为答案。
一下是AC代码:
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> using namespace std; int n,m,mmin[50001][17],mmax[50001][17],ansmax,ansmin; int gi() { int ans=0,f=1; char i=getchar(); while(i<'0'||i>'9'){if(i=='-')f=-1;i=getchar();} while(i>='0'&&i<='9'){ans=ans*10+i-'0';i=getchar();} return ans*f; } int main() { int i,j; n=gi();m=gi(); for(i=1;i<=n;i++)mmax[i][0]=mmin[i][0]=gi(); int op=log2(n); for(i=1;i<=op;i++) { for(j=1;j<=n;j++) if(j+(1<<i)-1<=n) { mmin[j][i]=min(mmin[j][i-1],mmin[j+(1<<i-1)][i-1]); mmax[j][i]=max(mmax[j][i-1],mmax[j+(1<<i-1)][i-1]); } } for(i=1;i<=m;i++) { int l=gi(),r=gi(),k=r-l+1; k=log2(k); ansmax=max(mmax[l][k],mmax[r-(1<<k)+1][k]); ansmin=min(mmin[l][k],mmin[r-(1<<k)+1][k]); printf("%d ",ansmax-ansmin); } return 0; }