线段树(自敲:建树,查找最大值,更新结点值)
HDU1754
1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 const int MaxSIZE = 2e6 + 10; 6 7 typedef struct { 8 int Max ; 9 int left, right ; 10 } NODE ; 11 12 int n, m ; 13 int num [MaxSIZE] ; 14 NODE tree[MaxSIZE * 20] ; 15 16 17 int build (int root, int left, int right) { 18 int mid ; 19 20 tree[root].left = left ; 21 tree[root].right = right ; 22 23 if (left == right) { 24 return tree[root].Max = num[left] ; 25 } 26 mid = (left + right) / 2 ; 27 28 29 int a, b ; 30 a = build (2 * root, left, mid) ; 31 b = build (2 * root + 1, mid + 1, right) ; 32 33 return tree[root].Max = max (a, b) ; 34 } 35 36 int Find (int root, int left, int right) { 37 int mid ; 38 39 if (tree[root].left > right || tree[root].right < left) 40 return 0 ; 41 42 if (left <= tree[root].left && tree[root].right <= right) 43 return tree[root].Max ; 44 45 int a, b ; 46 a = Find (2 * root, left, right) ; 47 b = Find (2 * root + 1, left, right) ; 48 49 return max (a, b) ; 50 } 51 52 53 int update (int root, int pos, int val) { 54 55 if (pos < tree[root].left || tree[root].right < pos) 56 return tree[root].Max ; 57 58 if (tree[root].left == pos && tree[root].right == pos) 59 return tree[root].Max = val ; 60 61 int a, b ; 62 a = update (2 * root, pos, val) ; 63 b = update (2 * root + 1, pos, val) ; 64 65 tree[root].Max = max (a, b) ; 66 67 return tree[root].Max ; 68 } 69 70 71 int main() { 72 int n, ask_n; 73 while (~scanf("%d%d", &n, &ask_n)) { 74 //while (cin >> n >> ask_n) { 75 memset(num, 0, sizeof(num)); 76 77 for (int i = 1; i <= n; ++ i) { 78 //cin >> num[i]; 79 scanf("%d", &num[i]); 80 } 81 82 build (1, 1, n); 83 84 char op; int x, y; 85 86 for (int j = 0; j < ask_n; ++ j) { 87 getchar(); 88 scanf("%c%d%d", &op, &x, &y); 89 //cin >> op >> x >> y; 90 if (op == 'Q') { 91 int ans = Find (1, x, y); 92 cout << ans << endl; 93 } else if (op == 'U') { 94 num[x] = y; 95 update (1, x, y); 96 } 97 } 98 } 99 return 0; 100 }