线段树模板

来源:互联网 发布:qq飞车极夜大黄蜂数据 编辑:程序博客网 时间:2024/06/03 05:07
#include<stdio.h>
#include<iostream>
int max(int x,int y)
{
  return x>y?x:y;
}
int a[300000];
struct ele
{
    int Left;
    int Right;
    int Max;
    int Sum;
}p[700000];
void Build(int L,int R,int Step)
{
    p[Step].Left=L;
    p[Step].Right=R;
    if(L==R)
        p[Step].Sum=p[Step].Max=a[L];
    else
    {
        int Mid=(L+R)/2;
        Build(L,Mid,2*Step);
        Build(Mid+1,R,2*Step+1);
        p[Step].Max=max(p[Step*2].Max,p[Step*2+1].Max);
        p[Step].Sum=p[Step*2].Sum+p[Step*2+1].Sum;
    }
}
void Update(int x,int y,int Step)
{
    if(p[Step].Left==x&&p[Step].Right==x)
        p[Step].Max=p[Step].Sum=y;
     else
    {
        int Mid=(p[Step].Left+p[Step].Right)/2;
        if(x<=Mid)
            Update(x,y,2*Step);
        else
            Update(x,y,2*Step+1);
        p[Step].Max=max(p[Step*2].Max,p[Step*2+1].Max);
        p[Step].Sum=p[Step*2].Sum+p[Step*2+1].Sum;
    }
}
int Max(int x,int y,int Step)
{
    if(p[Step].Left==x&&p[Step].Right==y)
        return p[Step].Max;
    else
    {
        int Mid=(p[Step].Left+p[Step].Right)/2;
        if(y<=Mid)
            return Max(x,y,2*Step);
        else
        if(x>=Mid+1)
            return Max(x,y,2*Step+1);
        else
            return max(Max(x,Mid,2*Step),Max(Mid+1,y,2*Step+1));
    }
}
int Sum(int x,int y,int Step)
{
    if(p[Step].Left==x&&p[Step].Right==y)
        return p[Step].Sum;
    else
    {
        int Mid=(p[Step].Left+p[Step].Right)/2;
        if(y<=Mid)
            return Sum(x,y,2*Step);
        else
        if(x>=Mid+1)
            return Sum(x,y,2*Step+1);
        else
            return Sum(x,Mid,2*Step)+Sum(Mid+1,y,2*Step+1);
    }
}
int main()
{
    int n,m;
    int i,j,k;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(i=1;i<=n;i++)
            scanf("%d",&a[i]);
        Build(1,n,1);
        while(m--)
        {
            scanf("%d%d%d",&i,&j,&k);
            if(i==1)
                Update(j,k,1);
            if(i==2)
                printf("%d\n",Sum(j,k,1));
            if(i==3)
                printf("%d\n",Max(j,k,1));
        }
    }
    return 0;
}
0 0