hdu1754 I Hate It (线段树)

来源:互联网 发布:今日头条优化助手 编辑:程序博客网 时间:2024/06/04 22:46
/*线段树 水题 模板套过*/#include <iostream>#include<cstdio>#include<cstring>using namespace std;#define max(a,b) a>b?a:bstruct LineTree{    int left,right;//左右区间端点    int highest;//区间最大值    LineTree *lchild,*rchild;};LineTree mem[400010];int pos;int score[200010];LineTree *NewTree()    //自己做的时候内存一直超,这是网上学到的,还不是很明白{    LineTree *s=&mem[pos++];//如此分配空间    return s;}LineTree* CreateTree(int a,int b)  //建立线段树{    LineTree *root=NewTree();    root->left=a;    root->right=b;    if(b-a>1)    {        int mid;        mid=(a+b)/2;        root->lchild=CreateTree(a,mid);        root->rchild=CreateTree(mid,b);        root->highest=max(root->lchild->highest,root->rchild->highest);    }    else        root->highest=max(score[root->left],score[root->right]);    return root;}int search(LineTree *t,int a,int b){    if(t->left==a && t->right==b)        return t->highest;    int mid=(t->left+t->right)/2;    if(b<=mid)  return search(t->lchild,a,b);    else if(mid<=a) return search(t->rchild,a,b);    else    {        int s1,s2;        s1=search(t->lchild,a,mid);        s2=search(t->rchild,mid,b);        return max(s1,s2);    }}void update(LineTree *t,int a){    if(t->right-t->left==1)    {        t->highest=max(score[t->left],score[t->right]);        return;    }    if(t->lchild->right>=a)        update(t->lchild,a);    if(t->rchild->left<=a)        update(t->rchild,a);    t->highest=max(t->lchild->highest,t->rchild->highest);    return;}int main(){    int n,m;    LineTree *s;    char ch;    int a,b;    while(scanf("%d%d",&n,&m)!=EOF)    {        pos=0;   //记得初始 - -!        int i;        for(i=1;i<=n;i++)            scanf("%d",&score[i]);        s=CreateTree(1,n);        getchar();        while(m--)        {            ch=getchar();            scanf("%d%d",&a,&b);            getchar();            if(ch=='Q')            {                if(a==b) printf("%d\n",score[a]);                else printf("%d\n",search(s,a,b));            }            else            {                score[a]=b;                update(s,a);            }        }    }    return 0;}