线段树,不带延迟的模板

#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
const int maxx = 200010;
int tree[maxx<<2];
int a[maxx];
int n;
void build(int root,int l,int r)
{
    //cout<<"root:"<<root<<" l,r:"<<l<<"  "<<r<<endl;
    if(l==r)
    {
        tree[root]=a[l];
    }
    else
    {
        int mid=(l+r)>>1;
        build(root<<1,l,mid);
        build((root<<1)+1,mid+1,r);
        tree[root]=max(tree[root<<1],tree[(root<<1)+1]);
    }
}
void update(int root,int l,int r,int pos,int val)
{
    if(pos==l&&pos==r)
    {
        tree[root]=val;
        return;
    }
    int mid=(l+r)>>1;
    if(pos<=mid) update(root<<1,l,mid,pos,val);
    else update((root<<1)+1,mid+1,r,pos,val);
    tree[root]=max(tree[root<<1],tree[(root<<1)+1]);
}
int query(int root,int l,int r,int ql,int qr)
{
    //cout<<"root:"<<root<<" l,r:"<<l<<"  "<<r<<" ql,qr "<<ql<<"  "<<qr<<"  tree[root] is :"<<tree[root]<<endl;
    if(l==ql&&qr==r)
    {
        return tree[root];
    }
    int mid=(l+r)>>1;
    if(qr<=mid)
    {
        return query(root<<1,l,mid,ql,qr);
    }
    else if(ql>mid)
    {
        return query((root<<1)+1,mid+1,r,ql,qr);
    }

    else return max(query(root<<1,l,mid,ql,mid),query((root<<1)+1,mid+1,r,mid+1,qr));
}
void print()
{
    int j=1,t=1;
    for(int i=1; i<=(n<<2); i++)
    {
        j++;
        printf("%d ",tree[i]);
        if(j>pow(2,(t-1)))
        {
            printf("\n");
            j=1;
            t++;
        }

    }
    printf("\n\n");
}
int main()
{
    int m;
    while(~scanf("%d%d",&n,&m))
    {
        for(int i=1; i<=n; i++)
        {
            scanf("%d",a+i);
        }
        build(1,1,n);

        char  cmd;
        for(int i=0; i<m; i++)
        {
            cin>>cmd;
            if(cmd=='U')
            {
                int tmp1,tmp2;
                scanf("%d%d",&tmp1,&tmp2);
                update(1,1,n,tmp1,tmp2);
            }
            else if(cmd=='Q')
            {
                int tmp1,tmp2;
                scanf("%d%d",&tmp1,&tmp2);
                int ans=query(1,1,n,tmp1,tmp2);
                printf("%d\n",ans);
            }
        }
    }
    return 0;
}

 

posted @ 2016-08-01 19:08  超级学渣渣  阅读(229)  评论(0编辑  收藏  举报