Link: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
AC code:
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<cmath> #include<queue> #define MAXN 200001 using namespace std; struct node{ int l; int r; int m; }tree[MAXN*4]; int num[MAXN],ans; void build(int rt,int s,int e) { tree[rt].l=s; tree[rt].r=e; if(s==e) { tree[rt].m=num[s]; return;//记得return!!! 否則下面回溯会出错!!! } int mid=(s+e)/2; build(rt*2,s,mid); build(rt*2+1,mid+1,e); tree[rt].m=max(tree[rt*2].m,tree[rt*2+1].m);//回溯,得出各区间最大值 } void update(int rt,int pos,int val) { int mid=(tree[rt].l+tree[rt].r)/2; if(tree[rt].l==pos&&tree[rt].r==pos) { tree[rt].m=val; return;//记得return!!! 否則下面回溯会出错!!! } else if(pos<=mid) { update(rt*2,pos,val); } else{ update(rt*2+1,pos,val); } tree[rt].m=max(tree[rt*2].m,tree[rt*2+1].m); } void query(int rt,int ql,int qr) { if(tree[rt].l==ql&&tree[rt].r==qr) { ans=max(ans,tree[rt].m); return;// 记得return!!! 否則下面回溯会出错!!! } int mid=(tree[rt].l+tree[rt].r)/2; if(ql>mid) { query(rt*2+1,ql,qr); } else if(qr<=mid) { query(rt*2,ql,qr); } else { query(rt*2,ql,mid); query(rt*2+1,mid+1,qr); } } int main() { int n,qm,i,x,y; char str[11]; while(scanf("%d%d",&n,&qm)!=EOF) { for(i=1;i<=n;i++) { scanf("%d",&num[i]); } build(1,1,n); while(qm--) { scanf("%s",str); if(str[0]=='Q') { scanf("%d%d",&x,&y); ans=-1; query(1,x,y); printf("%d\n",ans); } else { scanf("%d%d",&x,&y); update(1,x,y); } } } return 0; }