看了很长时间网上的代码,才知道大概的线段树模板,以后就照着这题抄模板好了,不过抽空还是自己独立写一次比较好。贴出来以备查用。
这道题代码出处:http://blog.youkuaiyun.com/panyanyany/article/details/6776300
讲解线段树博客地址:http://blog.youkuaiyun.com/metalseed/article/details/8039326
#include<iostream>
#include<stdio.h>
#include<math.h>
#define max(x1,x2) ((x1)>(x2)?(x1):(x2))
using namespace std;
const int maxn1 = 200005;
long long a[maxn1];
struct Node{
int max;
int left,right;
}tree[maxn1*20];
int build_tree(int root,int l,int r)
{
int mid;
tree[root].left = l;
tree[root].right = r;
if(l == r){
return tree[root].max= a[l];
}
mid = (l+r)/2;
int a,b;
a = build_tree(root*2,l,mid);
b = build_tree(root*2+1,mid+1,r);
return tree[root].max = max(a,b);
}
int find_tree(int root,int l,int r)
{
if(tree[root].left>r||tree[root].right<l)
return 0;
if(tree[root].left>=l&&tree[root].right<=r)
return tree[root].max ;
int c,d;
c = find_tree(root*2,l,r);
d = find_tree(root*2+1,l,r);
return max(c,d);
}
int update_tree(int root,int a,int b)
{
if(tree[root].left>a||tree[root].right<a)
return tree[root].max;
if(tree[root].left==a&&tree[root].right==a)
return tree[root].max = b;
int c,d;
c = update_tree(root*2,a,b);
d = update_tree(root*2+1,a,b);
return tree[root].max = max(c,d);
}
int main()
{
int n,m;
int x,y;
char c;
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
build_tree(1,1,n);
for(int i=0;i<m;i++)
{
getchar();
scanf("%c",&c);
scanf("%d%d",&x,&y);
if(c=='Q')
printf("%d\n",find_tree(1,x,y));
else {
a[x] = y;
update_tree(1,x,y);
}
}
}
return 0;
}