标签:
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 44820 Accepted Submission(s): 17591
分析:接触的第一条线段树的题目,也是一道线段树入门题,
线段树在一般的数据结构书上很少碰到,比较详细实用的可以参考一下这位大神在blog上写的解释:
AC代码:
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 5 #define maxn 800100 6 7 int tree[maxn]; 8 9 int max(int a, int b){ 10 return a > b ? a : b; 11 } 12 13 void build(int left,int right,int root){ 14 if (left == right) 15 scanf("%d",&tree[root]); 16 else{ 17 int mid = (left + right) >> 1; 18 build(left, mid, root << 1); 19 build(mid + 1, right, root << 1 | 1); 20 tree[root] = max(tree[root << 1], tree[root << 1 | 1]); 21 } 22 } 23 24 void update(int p, int element, int left, int right,int root){ 25 if (left == right) 26 tree[root] = element; 27 else{ 28 int mid = (left + right) >> 1; 29 if (p <= mid) 30 update(p, element, left, mid, root << 1); 31 else 32 update(p, element, mid + 1, right, root << 1 | 1); 33 tree[root] = max(tree[root << 1], tree[root << 1 | 1]); 34 } 35 } 36 37 int query(int a, int b, int left, int right, int root){ 38 if (a <= left&&b >= right) 39 return tree[root]; 40 else{ 41 int sum = 0, mid = (left + right) >> 1; 42 if (a <= mid) 43 sum = max(sum, query(a, b, left, mid, root << 1)); 44 if (b>mid) 45 sum = max(sum, query(a, b, mid + 1, right, root << 1 | 1)); 46 return sum; 47 } 48 } 49 50 int main() 51 { 52 int n, m, i, a, b; 53 char c; 54 while (scanf("%d%d", &n, &m) != EOF){ 55 build(1, n, 1); 56 for (i = 0; i < m; i++){ 57 getchar(); 58 scanf("%c%d%d",&c,&a,&b); 59 if (c == ‘U‘) 60 update(a, b, 1, n, 1); 61 else 62 printf("%d\n", query(a, b, 1, n, 1)); 63 } 64 } 65 return 0; 66 }
标签:
原文地址:http://www.cnblogs.com/lxzd723/p/4405593.html