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
思路:
对每次询问每次遍历查找肯定会超时(n*m = 50,000*200,000)(10^6 = 1000ms) 那么如果将对应的遍历变成二分的形式,即每次查找最大最最小,只需要两半区间两半的找,那么时间为(logn*m = 15.6*200,000)大概最坏情况3*10^6 = 3000ms 就可以在时间范围之内完成
很自然的,我们可以想到使用线段树,对于每次查询,只要查找对应区间的最值即可,而无需再遍历查找。
code:
#include
#include
using namespace std;
const int MAXN = 50000+5;
int arr[MAXN];
//对应借点的左区间,右区间
struct node{
int left,right;
int maxh;//这个区间里的最大,最小值
int minh;
};
const int INF =0x3f3f3f3f;
node st[MAXN<<2];//四倍空间
//建树,左闭右开 [start,end)
node build(int start,int end,int id){
st[id].left = start;
st[id].right = end;
//子树的话直接返回即可 如[3,4) 4是取不到的
if(end - start==1){
st[id].maxh = arr[start];
st[id].minh = arr[start];
return st[id];
}
int mid = (start+end)/2;
//递归建树
node temp1 = build(start,mid,id*2);
node temp2 = build(mid,end,id*2+1);
st[id].maxh = max(temp1.maxh,temp2.maxh);
st[id].minh = min(temp1.minh,temp2.minh);
return st[id];
}
//查询, 注意这里的 [start,end) 是查询的区间
node query(int start,int end,int id){
node out;
//等于好是因为没有交集,这里需要注意左闭右开
if(end<=st[id].left || start>=st[id].right) {
out.maxh = -1;
out.minh = INF;
return out;
}
//在这个查询范围内直接返回这个子树区间的最值即可
if(start<=st[id].left && end>=st[id].right){
return st[id];
}
node temp1 = query(start,end,id*2);
node temp2 = query(start,end,id*2+1);
out.maxh = max(temp1.maxh,temp2.maxh);
out.minh = min(temp1.minh,temp2.minh);
return out;
}
int N,Q;
int main(){
scanf("%d%d",&N,&Q);
for(int i=1;i<=N;i++){
scanf("%d",&arr[i]);
}
//[1,n+1)
build(1,N+1,1);
for(int i=0;i