http://acm.hdu.edu.cn/showproblem.php?pid=1754
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
5 6 5 9HintHuge input,the C function scanf() will work better than cin
#include <iostream> #include<cstdio> using namespace std; int n,m; struct tree { int l,r,key; } node[600000]; int score[600000]; int X,Y; int max(int x,int y) { return x>y?x:y; } int build(int l,int r,int i) //建树 { int mid=(l+r)/2; node[i].l=l; node[i].r=r; if(l==r) { node[i].key=score[l]; return node[i].key; } else { node[i].key=max(build(l,mid,2*i),build(mid+1,r,2*i+1)); //子节点中的最大值给父亲。 return node[i].key; } } void update(int i,int x,int key) { node[i].key=max(node[i].key,key); int mid=(node[i].l+node[i].r)/2; if(node[i].l==node[i].r) return ; if(x>mid) update(2*i+1,x,key); //x>mid往右边的节点找 else update(2*i,x,key); } int Quetion(int i,int l,int r) { if(node[i].l==l&&node[i].r==r) return node[i].key; else { int mid=(node[i].l+node[i].r)/2; if(l<=mid&&r>=mid+1) { return max(Quetion(2*i,l,mid),Quetion(2*i+1,mid+1,r)); } else if(l>=mid+1) { return Quetion(2*i+1,l,r); } else { return Quetion(2*i,l,r); } } } int main() { char ch; int a,b; while(scanf("%d %d",&n,&m)!=EOF) { int i; for(i=1; i<=n; i++) scanf("%d",&score[i]); build(1,n,1); while(m--) { getchar(); scanf("%c %d %d",&ch,&a,&b); if(ch=='U') update(1,a,b); else printf("%d\n",Quetion(1,a,b)); } } return 0; }
杭电 1754 I Hate It(线段树求最值),布布扣,bubuko.com
原文地址:http://blog.csdn.net/u012766950/article/details/38518701