poj p3264——Balanced Lineup(线段树)
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
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
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
这题说白了就直接线段树,而且比其他的简单。因为,此题要找的是最大高度差,所以只用在结构体中再加上u区间的最大高度和最矮高度就可以了,连update,pushdown,pushup都不用(O(∩_∩)O哈哈哈~开心ing~)
第一次交的时候超时了,后来把iosxxxxx和cin、cout换成scanf和printf,就刚好过了:
#include<cstdio>
#include<iostream>
#include<cmath>
#define MAXN 50005
#define R(u) (2*u+1)
#define L(u) (2*u)
using namespace std;
int m,n;int ans1,ans2;
struct node{
int high;int low;
int l,r;
}s[MAXN*4];
int a[MAXN];
void buildtree(int u,int left,int right)
{
s[u].l=left,s[u].r=right;
if(s[u].l==s[u].r)
{
s[u].high=a[left];
s[u].low=a[left];
return ;
}
int mid=(s[u].l+s[u].r)>>1;
buildtree(L(u),left,mid);
buildtree(R(u),mid+1,right);
s[u].high=max(s[L(u)].high,s[R(u)].high);
s[u].low=min(s[L(u)].low,s[R(u)].low);
}
void findhl(int u,int left,int right)
{
if(s[u].l==left&&s[u].r==right)
{
ans1=min(ans1,s[u].low);
ans2=max(ans2,s[u].high);
return ;
}
int mid=(s[u].l+s[u].r)>>1;
if(left>mid)
findhl(R(u),left,right);
else if(right<=mid)
findhl(L(u),left,right);
else
{
findhl(R(u),mid+1,right);
findhl(L(u),left,mid);
}
}
int main()
{
//ios::sync_with_stdio(false);
scanf("%d%d",&m,&n);//cin>>m>>n;
for(int i=1;i<=m;i++)
scanf("%d",&a[i]);//cin>>a[i];
buildtree(1,1,m);
for(int i=1;i<=n;i++)
{
ans1=999999;ans2=0;
int x,y;scanf("%d%d",&x,&y);//cin>>x>>y;
findhl(1,x,y);
printf("%d\n",ans2-ans1);//cout<<ans2-ans1<<endl;
}
return 0;
}