初学线段树。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cmath> 5 #define N 100000 6 using namespace std; 7 int n,m,ans; 8 int segtree[N*8],a[N*8]; 9 void adddata(int now) 10 { 11 segtree[now]=max(segtree[(now<<1)],segtree[(now<<1)+1]); 12 } 13 void buildtree(int now,int l,int r) 14 { 15 if (l==r) {segtree[now]=a[l]; return;} 16 int mid=(l+r)>>1; 17 buildtree((now<<1),l,mid); 18 buildtree((now<<1)+1,mid+1,r); 19 adddata(now); 20 } 21 void query(int now,int l,int r,int begin,int end) 22 { 23 if (begin<=l && end>=r) {ans=max(ans,segtree[now]);return;} 24 int mid=(l+r)>>1; 25 if (begin<=mid) query((now<<1),l,mid,begin,end); 26 if (end>mid) query((now<<1)+1,mid+1,r,begin,end); 27 } 28 void pointchange(int now,int l,int r,int x,int v) 29 { 30 if (l==r) {segtree[now]=v; return;} 31 int mid=(l+r)>>1; 32 if (x<=mid) pointchange((now<<1),l,mid,x,v); 33 else pointchange((now<<1)+1,mid+1,r,x,v); 34 adddata(now); 35 } 36 int main() 37 { 38 int i; 39 int x,y; 40 char s[10]; 41 while (~scanf("%d%d",&n,&m)) 42 { 43 memset(segtree,0,sizeof(0)); 44 memset(a,0,sizeof(0)); 45 for (i=1;i<=n;i++) scanf("%d",&a[i]); 46 buildtree(1,1,n); 47 for (i=1;i<=m;i++) 48 { 49 scanf("%s %d %d",s,&x,&y); 50 if (s[0]=='Q') {ans=0;query(1,1,n,x,y);printf("%d ",ans);} 51 else pointchange(1,1,n,x,y); 52 } 53 } 54 return 0; 55 }