poj3264 Balanced Lineup

线段树,第一次写,2516K 1829MS

 

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<algorithm>
using namespace std;
int cow[50005];
#define my_max 1000010
#define my_min -1000010
int resmax;
int resmin;
struct node
{
    int nmax;
    int nmin;
    int L;
    int R;
    node *left;
    node *right;
};
node tree[100010];
int ncount=0;//总结点数目
void build_tree(node *p,int L,int R)
{
    p->L=L;
    p->R=R;
    p->nmax=my_min;
    p->nmin=my_max;
    if(L!=R)
    {
        ncount++;
        p->left=tree+ncount;
        ncount++;
        p->right=tree+ncount;
        build_tree(p->left,L,(L+R)/2);
        build_tree(p->right,(L+R)/2+1,R);
    }
}
void insert(node *p,int i,int val)
{
    if(p->L==i&&p->R==i)
    {
        p->nmin=val;
        p->nmax=val;
        return;
    }
    p->nmin=(p->nmin)<val?(p->nmin):val;
    p->nmax=(p->nmax)>val?p->nmax:val;
    if(i<=(p->L+p->R)/2)
    {
        insert(p->left,i,val);
    }
    else
    {
        insert(p->right,i,val);
    }
}
void query(node *p,int L,int R)
{
    if(p->nmin>=resmin&&p->nmax<=resmax)
    {
        return;
    }
    if(p->L==L&&p->R==R)
    {
        resmax=(p->nmax)>resmax?(p->nmax):resmax;
        resmin=(p->nmin)<resmin?(p->nmin):resmin;
        return;
    }
    if(R<=(p->L+p->R)/2)
    {
        query(p->left,L,R);
    }
    else if(L>=(p->L+p->R)/2+1)
    {
        query(p->right,L,R);
    }
    else
    {
        query(p->left,L,(p->L+p->R)/2);
        query(p->right,(p->L+p->R)/2+1,R);
    }
}
int main()
{
    int N,Q;
    scanf("%d %d",&N,&Q);
    build_tree(tree,1,N);
    int temp;
    int i;
    for(i=1;i<=N;i++)
    {
        scanf("%d",&temp);
        insert(tree,i,temp);
    }
    for(i=0;i<Q;i++)
    {
        int l,r;
        scanf("%d%d",&l,&r);
        resmax=my_min;
        resmin=my_max;
        query(tree,l,r);
        printf("%d\n",resmax-resmin);
    }
    return 0;
}

posted @ 2012-07-16 21:06  willzhang  阅读(119)  评论(0编辑  收藏  举报