Description
Input
Output
Sample Input
5 6 1 2 3 4 5 Q 1 5 U 3 6 Q 3 4 Q 4 5 U 2 9 Q 1 5
Sample Output
5 6 5 9我的线段树第二个题,昨天晚上做了第一个题,是求和的,看到这个题的时候,发现这个求最大值和求和是一样的,从叶子节点一直往根节点传最大值,稍微改一下就A了。LANGUAGE:C++CODE:#include<iostream> #include<cstdio> #include<algorithm> #include<cctype> using namespace std; int tree[800005]; void build(int left,int right,int root) { if(left==right) { scanf("%d",&tree[root]); } else { int mid=(left+right)>>1; build(left,mid,root<<1); build(mid+1,right,root<<1|1); tree[root]=max(tree[root<<1],tree[root<<1|1]); } } void update(int p,int add,int left,int right,int root) { if(left==right) { tree[root]=add; } else { int mid=(left+right)>>1; if(p<=mid)update(p,add,left,mid,root<<1); else update(p,add,mid+1,right,root<<1|1); tree[root]=max(tree[root<<1],tree[root<<1|1]); } } int query(int x,int y,int left,int right,int root) { if(x<=left&&right<=y) { return tree[root]; } else { int sum=0,mid=(left+right)>>1; if(x<=mid)sum=max(sum,query(x,y,left,mid,root<<1)); if(y>mid)sum=max(sum,query(x,y,mid+1,right,root<<1|1)); return sum; } } int main() { //freopen("in.txt","r",stdin); int n,m; while(scanf("%d%d",&n,&m)!=EOF) { build(1,n,1); while(m--) { char o[3]; int x,y; scanf("%s%d%d",o,&x,&y); if(o[0]=='U') update(x,y,1,n,1); else printf("%d\n",query(x,y,1,n,1)); } } return 0; }