标签:
最近开始重新学习线段树,先从最简单的开始吧!
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 46762 Accepted Submission(s): 18316
分析:线段树的基本操作,单点更新与区间查询。交上去开始RE了,后来发现是数组开小了└(T_T;)┘
//simonPR #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define lid (2*id) #define rid (2*id+1) #define mid ((tr[id].l+tr[id].r)/2) using namespace std; const int maxn=200010; int student[maxn]; struct segtree{ int l,r,maxs; }; segtree tr[4*maxn]; void build (int id,int l,int r); void push_on(int id); void update(int id,int b); void build (int id,int l,int r){ tr[id].l=l; tr[id].r=r; if(l==r){ tr[id].maxs=student[l]; return; } build(lid,l,mid); build(rid,mid+1,r); push_on(id); } void push_on(int id){ tr[id].maxs=max(tr[lid].maxs,tr[rid].maxs); } void update(int id,int a,int b){ if(tr[id].l==a&&tr[id].r==a){ tr[id].maxs=b; return; } if(a>mid) update(rid,a,b); else update(lid,a,b); push_on(id); } int query(int id,int l,int r){ if(tr[id].l==l&&tr[id].r==r){ return tr[id].maxs; } if(l>mid) return query(rid,l,r); else if(r<=mid) return query(lid,l,r); else return max(query(lid,l,mid),query(rid,mid+1,r)); } int main() { int n,m; while(scanf("%d%d",&n,&m)!=EOF){ for(int i=1;i<=n;i++) scanf("%d",&student[i]); build(1,1,n); char op[1]; int a,b; while(m--){ scanf("%s",op); if(op[0]==‘U‘){ scanf("%d%d",&a,&b); update(1,a,b); } if(op[0]==‘Q‘){ scanf("%d%d",&a,&b); int maxst=query(1,a,b); printf("%d\n",maxst); } } } return 0; }
标签:
原文地址:http://www.cnblogs.com/RRirring/p/4540636.html