您的位置:首页 > 其它

线段树模板

2015-06-05 16:21 363 查看
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
const int MAXNODE = 524288; // 1<<19
const int MAXST = 200001;
int father[MAXST];
struct STU
{
int value;
int left,right;
}st[MAXNODE];

void buildtree(int i,int left,int right)
{
st[i].value=0;
st[i].left=left;
st[i].right=right;
if(left==right)
{
father[left]=i;
return;
}
buildtree(i<<1,left,(left+right)/2);
buildtree((i<<1)+1,(left+right)/2+1,right);

}
void updatetree(int ri)//ri为节点
{
if(ri==1)
{
return ;
}
int fi=ri/2;
int a = st[fi<<1].value;
int b = st[(fi<<1)+1].value;
st[fi].value = max(a,b);
updatetree(ri/2);
}
int Max;
void Query(int i,int l,int r)
{
if(st[i].left == l && st[i].right==r)
{
Max = max(Max,st[i].value);
return ;
}
i=i<<1;
if(l<=st[i].right)
{
if(r<=st[i].right)
Query(i,l,r);
else
Query(i,l,st[i].right);
}
i+=1;
if(r>=st[i].left)
{
if(l>st[i].left)
Query(i,l,r);
else
Query(i,st[i].left,r);

}

}
int main()
{
int n,q,temp;
while(~scanf("%d %d",&n,&q))
{
buildtree(1,1,n);
for(int i=1;i<=n;i++)
{
scanf("%d",&temp);
st[father[i]].value = temp;
updatetree(father[i]);
}
while(q--)
{
char o[3];
int a,b;
scanf("%s %d %d",o,&a,&b);
if(o[0] == 'Q')
{
Max=0;
Query(1,a,b);
printf("%d\n",Max );
}else
{
st[father[a]].value=b;
updatetree(father[a]);
}
}

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