您的位置:首页 > 其它

POJ_3264: Balanced Lineup线段树入门

2016-08-26 10:21 316 查看

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

只需要建树时,树中同时存最大最小值,用参数hehe来区别查询最大最小值,最后相减

#include<iostream>
#include<cstdio>
using namespace std;
int num[50005];
struct tree
{
int maxm,minn;
}tree[50005*4];
int n,k;
void build(int index,int left,int right)
{
if(left==right)
{
tree[index].maxm=tree[index].minn=num[right];
return ;
}
int mid=(left+right)/2;
build(index*2+1,left,mid);
build(index*2+2,mid+1,right);
tree[index].maxm=max(tree[index*2+1].maxm,tree[index*2+2].maxm);
tree[index].minn=min(tree[index*2+1].minn,tree[index*2+2].minn);
}

void change(int index,int left,int right,int val,int i)
{
if(left==right)
{
tree[index].maxm=tree[index].minn=val;
return ;
}
int mid=(left+right)/2;
if(i<=mid)
change(index*2+1,left,mid,val,i);
else if(i>mid)
change(index*2+2,mid+1,right,val,i);
tree[index].maxm=max(tree[index*2+1].maxm,tree[index*2+2].minn);
tree[index].minn=min(tree[index*2+1].minn,tree[index*2+2].minn);
}
int query(int index,int left,int right,int x,int y,bool hehe)
{
if(x==left&&y==right)
{
if(!hehe)return tree[index].maxm;
return tree[index].minn;
}
int mid=(left+right)/2;
if(y<=mid)
return query(index*2+1,left,mid,x,y,hehe);
else if(x>mid)
return query(index*2+2,mid+1,right,x,y,hehe);
else
{
if(!hehe)return max(query(index*2+1,left,mid,x,mid,hehe),query(index*2+2,mid+1,right,mid+1,y,hehe));
return min(query(index*2+1,left,mid,x,mid,hehe),query(index*2+2,mid+1,right,mid+1,y,hehe));
}
}
int main()
{
while(scanf("%d%d",&n,&k)!=-1)
{
for(int i=1; i<=n; i++)
scanf("%d",&num[i]);
int x,y;
build(0,1,n);
for(int i=0; i<k; i++)
{
scanf("%d%d",&x,&y);
printf("%d\n",query(0,1,n,x,y,0)-query(0,1,n,x,y,1));
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息