[HDU1754]I Hate It线段树裸题
http://acm.hdu.edu.cn/showproblem.php?pid=1754
解题关键:刚开始死活超时,最后发现竟然是ch,和t1、t2每次循环都定义的锅,以后养成建全局变量的习惯。
注意背模板时,find时最后无赋值
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 struct node{ 5 int left,right,max; 6 }tree[800002]; 7 int num[200002]; 8 char ch; 9 int t1,t2; 10 int build(int root,int left,int right){ 11 tree[root].left=left; 12 tree[root].right=right; 13 if(left==right) return tree[root].max=num[left]; 14 15 int a,b,mid; 16 mid=(left+right)/2; 17 a=build(2*root,left,mid); 18 b=build(2*root+1,mid+1,right); 19 return tree[root].max=max(a,b); 20 } 21 22 int find(int root,int left,int right){ 23 if(right<tree[root].left||left>tree[root].right) return 0; 24 if(left<=tree[root].left&&tree[root].right<=right) return tree[root].max; 25 26 int a,b; 27 a=find(2*root,left,right); 28 b=find(2*root+1,left,right); 29 return max(a,b);//find时不能赋值 30 } 31 32 int update(int root,int pos,int val){ 33 if(pos<tree[root].left||pos>tree[root].right) return tree[root].max; 34 if(pos==tree[root].left&&pos==tree[root].right) return tree[root].max=val; 35 36 int a,b; 37 a=update(2*root,pos,val); 38 b=update(2*root+1,pos,val); 39 return tree[root].max=max(a,b); 40 } 41 int n,m; 42 int main(){ 43 while(scanf("%d%d",&n,&m)!=EOF){ 44 memset(num,0,sizeof num); 45 memset(tree,0,sizeof tree); 46 for(int i=1;i<=n;i++){ 47 scanf("%d",num+i); 48 } 49 build(1,1,n); 50 for(int i=0;i<m;i++){ 51 getchar(); 52 scanf("%c%d%d",&ch,&t1,&t2); 53 if(ch=='Q'){ 54 int res=find(1,t1,t2); 55 printf("%d\n",res); 56 } 57 else{ 58 update(1,t1,t2); 59 } 60 } 61 } 62 63 }