【线段树】I Hate It

P1531
做的第一个线段树题目,完全模板,还被字符读入坑了一下……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<stdio.h>
struct node{
int val;
};
struct node segtree[200005*4];
int a[200005]={0};
int max(int a,int b){
if(a>b)return a;
return b;
}

void build(int rt,int st,int ed){
if(st==ed)
segtree[rt].val=a[st];
else{
int mid=(st+ed)/2;
build(rt*2,st,mid);
build(rt*2+1,mid+1,ed);
segtree[rt].val=max(segtree[rt*2].val,segtree[rt*2+1].val);
}
}

int query(int rt,int nst,int ned,int qst,int qed){
if(qst>ned||qed<nst)
return 0;
if(qst<=nst&&qed>=ned)
return segtree[rt].val;
int mid=(nst+ned)/2;
return max(query(rt*2,nst,mid,qst,qed),query(rt*2+1,mid+1,ned,qst,qed));
}

void updateone(int rt,int nst,int ned,int index,int addval){
if(nst==ned){
if(nst==index)
segtree[rt].val=addval;
return;
}
int mid=(nst+ned)/2;
if(index<=mid)
updateone(rt*2,nst,mid,index,addval);
else updateone(rt*2+1,mid+1,ned,index,addval);
segtree[rt].val=max(segtree[rt*2].val,segtree[rt*2+1].val);
}

int main(){
int n,m,i,x,y;
char type[10];
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
getchar();
for(i=1;i<=m;i++){
scanf("%s",type);
if(type[0]=='Q'){
scanf("%d%d",&x,&y);
printf("%d\n",query(1,1,n,x,y));
}
else{
scanf("%d%d",&x,&y);
if(a[x]<y){
a[x]=y;
updateone(1,1,n,x,y);
}
}
getchar();
}
return 0;
}