您的位置:首页 > 其它

Balanced Lineup(poj3264,线段树入门)

2013-08-15 09:57 363 查看
/*http://poj.org/problem?id=3264

Balanced Lineup

Time Limit: 5000MS Memory Limit: 65536K

Total Submissions: 28613 Accepted: 13461

Case Time Limit: 2000MS

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

Source

USACO 2007 January Silver

Accepted 2392K 2000MS C++ 1558B

*/

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include <iostream>
using namespace std;
const int maxn=50000+10;
int a[maxn];
int min(int a,int b){return a<b? a:b;}
int max(int a,int b){return a>b? a:b;}
struct  Tree
{
int l;
int r;
int minv;
int maxv;
}tr[maxn*4];
void build(int k,int l,int r)
{
tr[k].l=l;
tr[k].r=r;
if(l==r)
{
tr[k].minv=a[l];
tr[k].maxv=a[l];
return;
}
int mid=(l+r)/2;
build(k<<1,l,mid);
build(k<<1|1,mid+1,r);
tr[k].minv=min(tr[k<<1].minv,tr[k<<1|1].minv);
tr[k].maxv=max(tr[k<<1].maxv,tr[k<<1|1].maxv);
return;
}
int fmin(int k,int s,int t)
{
if(tr[k].l==s&&tr[k].r==t)
{
return tr[k].minv;
}
int mid=(tr[k].l+tr[k].r)/2;
if(t<=mid)
{return	 fmin(k<<1,s,t);}
else if(s>mid)
{return fmin(k<<1|1,s,t);}
else
{
return	min(fmin(k<<1,s,mid),fmin(k<<1|1,mid+1,t));
}
}
int fmax(int k,int s,int t)
{
if(tr[k].l==s&&tr[k].r==t)
{
return tr[k].maxv;
}
int mid=(tr[k].l+tr[k].r)/2;
if(t<=mid)
{return	 fmax(k<<1,s,t);}
else if(s>mid)
{return fmax(k<<1|1,s,t);}
else
{
return	max(fmax(k<<1,s,mid),fmax(k<<1|1,mid+1,t));
}
}
int main()
{  int i,j,n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
int s,t,ans;
for(i=0;i<m;i++)
{
scanf("%d%d",&s,&t);
if(s==t)
{
printf("0\n");
continue;
}
ans=fmax(1,s,t)-fmin(1,s,t);
printf("%d\n",ans);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: