您的位置:首页 > 其它

线段树模板

2014-07-21 08:03 316 查看
#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: