您的位置:首页 > 其它

Balanced Lineup POJ - 3264

2017-06-21 21:18 344 查看
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

题意:求给定区间最大值与最小值的差值,线段树小变形,回溯的时候把最大值最小值求出来.我比较懒,其实可以不用查询两次把最大值最小值分别查询出来,可以设置两个变量,一波就查出来.不过除了常数大一点,也没什么.
#include<cstdio>
#include<algorithm>
using namespace std;
const int M=60000;
struct aa
{
int maxx,minn;
} tree[4*M];
int save[M];
void creat(int l,int r,int now)
{
if(l==r)
{
tree[now].maxx=tree[now].minn=save[l];
return;
}
else
{
int mid=(r+l)/2;
creat(l,mid,now*2+1);
creat(mid+1,r,now*2+2);
tree[now].minn=min(tree[now*2+1].minn,tree[now*2+2].minn);
tree[now].maxx=max(tree[now*2+1].maxx,tree[now*2+2].maxx);

}
}
int query(int l,int r,int now,int ql,int qr,bool type)//1最大,0最小
{
if(ql<=l&&qr>=r)
{
if(type==1)
return tree[now].maxx;
else
return tree[now].minn;
}
if(ql>r||qr<l)
{
if(type==1)
return 0;
else
return 0x3f3f3f3f;
}
int mid=(l+r)/2;
if(type)
return max(query(l,mid,now*2+1,ql,qr,type),query(mid+1,r,now*2+2,ql,qr,type));
else
return min(query(l,mid,now*2+1,ql,qr,type),query(mid+1,r,now*2+2,ql,qr,type));

}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0; i<n; i++)
scanf("%d",&save[i]);
creat(0,n-1,0);
while(m--)
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",query(0,n-1,0,a-1,b-1,1)-query(0,n-1,0,a-1,b-1,0));
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: