POJ3264 Balanced Lineup

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 22665   Accepted: 10533
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


昨天吃完饭的时候,Dylan跟我说了下线段树,回来试了一下,居然过了,不过自己随手写的,太丑,估计还不能当模板,orz。

#include <stdio.h>
#include <algorithm>
using namespace std;

#define INF 999999999

typedef struct
{
    int l,r;
    int big,small;
}Tree;

Tree tree[500000];
int a[50005];

void Build(int t,int l,int r)
{
    int i,j,mid;
    tree[t].l=l;
    tree[t].r=r;
    if (l==r)
    {
        tree[t].big=tree[t].small=a[l];
        return;
    }
    mid=(l+r)/2;
    Build(2*t+1,l,mid);
    Build(2*t+2,mid+1,r);
    tree[t].big=max(tree[2*t+1].big,tree[2*t+2].big);
    tree[t].small=min(tree[2*t+1].small,tree[2*t+2].small);
}

void Query(int t,int x,int y,int &minn,int &maxn)
{
    int l,r,i,j,mid;
    l=tree[t].l;
    r=tree[t].r;
    if (l==x && r==y)
    {
        minn=tree[t].small;
        maxn=tree[t].big;
        return;
    }
    mid=(l+r)/2;
    if (mid>=y)
    {
        Query(2*t+1,x,y,minn,maxn);
    }
    else if (mid+1<=x)
    {
        Query(2*t+2,x,y,minn,maxn);
    }
    else
    {
        Query(2*t+1,x,mid,minn,maxn);
        Query(2*t+2,mid+1,y,i,j);
        minn=min(minn,i);
        maxn=max(maxn,j);
    }
}

int main()
{
    int i,j,n,x,y,minn,maxn,m;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for (i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        Build(0,0,n-1);
        for (i=0;i<m;i++)
        {
            scanf("%d%d",&x,&y);
            x--;
            y--;
            minn=INF;
            maxn=0;
            Query(0,x,y,minn,maxn);
            printf("%d\n",maxn-minn);
        }
    }
    return 0;
}





你可能感兴趣的:(struct,tree,Integer,query,Build,each)