POJ - 3264
POJ - 3264
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
题意:查找区间最值,输出差。
思路:可以用线段树或者st表,因为不用改值嘛。
code
#include <bits/stdc++.h>
using namespace std;
#define inf 1e5+10
#define long long ll
const int gm=50010;//st表查询区间最值
int minn[gm][20];
int maxn[gm][20];//最大值,表示[gm,gm+2^j-1],区间长度为2^j-1的最值
int main()
{
int n,q,k;
cin>>n>>q;
for (int i=0;i<n;i++)
{
scanf("%d",&minn[i][0]);
maxn[i][0]=minn[i][0];
}//j为0时,初值为自己
for (int j=0;(k=1<<(j+1))<n;j++)//2,4,8
{
for (int i=0;i+k<=n;i++)//0,1,2,3,4,5
{
minn[i][j+1]=min(minn[i][j],minn[i+(1<<j)][j]);
maxn[i][j+1]=max(maxn[i][j],maxn[i+(1<<j)][j]);//区间二分,2^(j+1)长度左右对分比较
}
}
int l=0,r=0;
while (q--)//查询
{
scanf("%d%d", &l, &r);
if (l==r)//如果就一个元素为0
{
printf("%d\n",0);
continue;
}
--l;//因为以0为开头记录下表,所以减
--r;
int len=r-l+1;//区间长度
int j;
for(j = 0; (1 << (j+1)) < len; ++j) ;//求log2(len)
printf("%d\n", max(maxn[l][j], maxn[r+1 - (1 << j)][j]) -
min(minn[l][j], minn[r+1 - (1 << j)][j]));//左端点开始的2^j长度和右端点向左的2^j长度,这样就全覆盖了
}
system("pause");
return 0;
}