poj 3264 Balanced Lineup 线段树

来源:互联网 发布:我是大主宰服务端源码 编辑:程序博客网 时间:2024/06/05 17:20

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 andQ.
Lines 2.. N+1: Line i+1 contains a single integer that is the height of cowi
Lines N+2.. N+ Q+1: Two integers A and B (1 ≤ABN), representing the range of cows from A toB 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 31734251 54 62 2
Sample Output
630

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;struct sr{    int l,r,maxs,mins;// 记录当前结点的最大值与最小值}t[800000];void build(int l,int r,int k){    t[k].l=l;    t[k].r=r;    t[k].maxs=0;    t[k].mins=0xfffffff;    if(t[k].r==t[k].l)    {        return ;    }    int mid=(l+r)>>1;    build(l,mid,k<<1);    build(mid+1,r,k<<1|1);}void insert(int n,int d,int k){    if(t[k].l==t[k].r&&d==t[k].l)    {        t[k].maxs=n;        t[k].mins=n;        return;    }    int mid=(t[k].l+t[k].r)>>1;    if(d<=mid)        insert(n,d,k<<1);    else        insert(n,d,k<<1|1);    t[k].maxs=max(t[k<<1].maxs,t[k<<1|1].maxs);    t[k].mins=min(t[k<<1].mins,t[k<<1|1].mins);}int ans,maxs,mins;void search(int l,int r,int k){    if(t[k].l==l&&t[k].r==r)    {        maxs=max(maxs,t[k].maxs);        mins=min(mins,t[k].mins);        ans=max(ans,maxs-mins);        return ;    }    int mid=(t[k].l+t[k].r)>>1;    if(r<=mid)    search(l,r,k<<1);    else        if(l>mid)        search(l,r,k<<1|1);    else        {            search(mid+1,r,k<<1|1);            search(l,mid,k<<1);        }}int main(){    int n,m;    int temp;    int a,b;    while(~scanf("%d%d",&n,&m))    {        build(1,n,1);        for(int i=1;i<=n;i++)        {            scanf("%d",&temp);            insert(temp,i,1);        }        for(int i=1;i<=m;i++)        {            scanf("%d%d",&a,&b);            ans=0;maxs=0,mins=0xfffffff;            search(a,b,1);            printf("%d\n",ans);        }    }    return 0;}



原创粉丝点击