I Hate It HDU - 1754 (线段树)
注意点:scanf中使用%c时,会读取空格和回车,所以在%c之前要有一个空格 ( 或者直接使用%s也行,%s会忽略空格和回车 )。具体见下面的代码:
1 #include<iostream> 2 #include<vector> 3 #include<string> 4 #include<cmath> 5 #include<set> 6 #include<algorithm> 7 #include<cstdio> 8 #include<map> 9 #include<cstring> 10 #include<list> 11 12 #define MAXSIZE 200010 13 14 using namespace std; 15 16 int N, M; 17 int tree[4*MAXSIZE]; 18 int ans = -1; 19 20 void init() 21 { 22 memset(tree, 0, sizeof(tree)); 23 } 24 25 26 void build(int node, int l, int r) 27 { 28 if(l == r) 29 { 30 scanf("%d", &tree[node]); 31 return; 32 } 33 int mid = (l+r)/2; 34 build(node*2, l, mid); 35 build(node*2+1, mid+1, r); 36 37 tree[node] = max(tree[node*2], tree[node*2+1]); 38 } 39 40 // 单点更新 41 void update(int node, int l, int r, int index, int n) 42 { 43 if(l == r) 44 { 45 tree[node] = n; 46 return; 47 } 48 int mid = (l+r)/2; 49 if(index <= mid) 50 update(node*2, l, mid, index, n); 51 else 52 update(node*2+1, mid+1, r, index, n); 53 54 tree[node] = max(tree[node*2], tree[node*2+1]); 55 } 56 57 58 // 区间查询 59 int query_range(int node, int l, int r, int L, int R) 60 { 61 if(l <= L && r >= R) 62 return tree[node]; 63 int mid = (L+R)/2; 64 if(l <= mid) 65 ans = max(ans, query_range(node*2, l, r, L, mid)); 66 if(mid < r) 67 ans = max(ans, query_range(node*2+1, l, r, mid+1, R)); 68 69 return ans; 70 } 71 72 int main() 73 { 74 while(scanf("%d%d", &N, &M) != EOF) 75 { 76 init(); 77 build(1,1,N); 78 for(int j = 0; j < M; ++j) 79 { 80 char c; 81 int a, b; 82 scanf(" %c%d%d", &c, &a, &b); // scanf中%c会读取空格和回车,所以在%c前面加一个空格 83 if(c == 'Q') 84 { 85 printf("%d\n", query_range(1, a, b, 1, N)); 86 ans = -1; 87 } 88 else if(c == 'U') 89 update(1, 1, N, a, b); 90 } 91 } 92 93 return 0; 94 }