poj 3264 线段树,链表实现

2017年02月24日 10点热度 0人点赞 0条评论
Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 48900   Accepted: 22901
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

 
 
ac代码
 
 
 
#include
#include
#include
using namespace std;
const int INF=99999999;
int mi,mx;
struct node{
 int l,r,minn,maxx;
 node *lchild,*rchild;
};
void buildtree(node* &root,int l,int r){
    root=(node*)malloc(sizeof(node));
    root->l=l;
    root->r=r;
    root->minn=INF;
    root->maxx=-INF;
    if(r==l) return;
    buildtree(root->lchild,l,(r+l)/2);
    buildtree(root->rchild,(r+l)/2+1,r);
}
void iinsert(node *root,int i,int v){
    if(root->l==root->r){
        root->maxx=root->minn=v;
        return;
    }
    root->minn=min(root->minn,v);
    root->maxx=max(root->maxx,v);
    if(i<=(root->l+root->r)/2)
        iinsert(root->lchild,i,v);
    else
        iinsert(root->rchild,i,v);
}
void Query(node *root,int s,int e){
    if(mi<=root->minn&&mx>=root->maxx) return ;
    if(s==root->l&&e==root->r){
        mi=min(root->minn,mi);
        mx=max(root->maxx,mx);
        return;
    }
    if(e<=(root->l+root->r)/2)
        Query(root->lchild,s,e);
    else if(s>(root->l+root->r)/2)
    Query(root->rchild,s,e);
    else{
        Query(root->lchild,s,(root->l+root->r)/2);
        Query(root->rchild,(root->l+root->r)/2+1,e);
    }
}
int main(){
    node* root;
    int n,q,h;
    cin>>n>>q;
     buildtree(root,1,n);
    for(int i=1;i<=n;i++){
        scanf("%d",&h);
        iinsert(root,i,h);
    }
    for(int i=1;i<=q;i++){
        int s,e;
        scanf("%d%d",&s,&e);
        mi=INF;
        mx=-INF;
        Query(root,s,e);
        printf("%dn",mx-mi);
    }
return 0;
}
未经允许不得转载!poj 3264 线段树,链表实现

update

纸上得来终觉浅, 绝知此事须躬行。