【POJ3264】Balanced Lineup,线段树入门

Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536K
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
写在前面:仅作了解
——————————————————————————————————————————————
思路:无

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct node
{
    int maxn,minn,x,y;
}tree[800010];
int n,q,x,y;
int head,tail;
int a[200010];
int in()
{
    int t=0;
    char ch=getchar();
    while (ch>'9'||ch<'0') ch=getchar();
    while (ch>='0'&&ch<='9') t=t*10+ch-'0',ch=getchar();
    return t;
}
void build_tree(int now,int l,int r)
{
    tree[now].x=l;tree[now].y=r;
    if (l==r) 
    {
        tree[now].maxn=tree[now].minn=a[l];
        return;
    }
    int mid=(l+r)/2;
    build_tree(now*2,l,mid);
    build_tree(now*2+1,mid+1,r);
    tree[now].maxn=max(tree[now*2].maxn,tree[now*2+1].maxn);
    tree[now].minn=min(tree[now*2].minn,tree[now*2+1].minn);
}
int findmin(int now,int begin,int end)
{
    if (begin>tail||end<head) return 9999999;
    if (begin>=head&&end<=tail) return tree[now].minn;
    int mid=(begin+end)/2;
    return min(findmin(now*2,begin,mid),findmin(now*2+1,mid+1,end));
}
int findmax(int now,int begin,int end)
{
    if (begin>tail||end<head) return -9999999;
    if (begin>=head&&end<=tail) return tree[now].maxn;
    int mid=(begin+end)/2;
    return max(findmax(now*2,begin,mid),findmax(now*2+1,mid+1,end));
}
main()
{
    n=in();q=in();
    for (int i=1;i<=n;i++) a[i]=in();
    build_tree(1,1,n);
    for (int i=1;i<=q;i++)
    {
        head=in();
        tail=in();
        printf("%d\n",findmax(1,1,n)-findmin(1,1,n));
    }
}

你可能感兴趣的:(【POJ3264】Balanced Lineup,线段树入门)