HDU 1166(线段树)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166

区间求和问题~~~

代码如下:

  1 #include <stdio.h>
  2 #include <string.h>
  3 #define N 50002
  4 #define L(x) ((x)<<1)
  5 #define R(x) ((x)<<1|1)
  6 
  7 typedef struct
  8 {
  9     int lson, rson;
 10     int val;
 11 } seg_tree;
 12 
 13 seg_tree s[N<<2];
 14 int a[N];
 15 
 16 int build(int left, int right, int idx)
 17 {
 18     s[idx].lson = left;
 19     s[idx].rson = right;
 20     if(left == right)
 21     {
 22         s[idx].val = a[left];
 23         return a[left];
 24     }
 25     int mid = (left + right) / 2;
 26     return s[idx].val = (build(left, mid, L(idx)) + build(mid + 1, right, R(idx)));
 27 }
 28 
 29 void update(int id, int idx, int val)
 30 {
 31     s[idx].val += val;
 32     if(s[idx].lson == s[idx].rson)
 33     {
 34         return;
 35     }
 36     int mid = (s[idx].lson + s[idx].rson) / 2;
 37     if(id <= mid)
 38     {
 39         update(id, L(idx), val);
 40     }
 41     else
 42     {
 43         update(id, R(idx), val);
 44     }
 45 }
 46 
 47 int query(int left, int right, int idx)
 48 {
 49     if(left == s[idx].lson && s[idx].rson == right)
 50     {
 51         return s[idx].val;
 52     }
 53     int mid = (s[idx].lson + s[idx].rson) / 2;
 54     if(right <= mid)
 55     {
 56         return query(left, right, L(idx));
 57     }
 58     else if(left > mid)
 59     {
 60         return query(left, right, R(idx));
 61     }
 62     else
 63     {
 64         return query(left, mid, L(idx)) + query(mid + 1, right, R(idx));
 65     }
 66 }
 67 
 68 int main()
 69 {
 70     int t;
 71     int n;
 72     int i, j;
 73     char str[10];
 74     scanf("%d", &t);
 75     for(i = 1; i <= t; i++)
 76     {
 77         scanf("%d", &n);
 78         for(j = 1; j <= n; j++)
 79         {
 80             scanf("%d", &a[j]);
 81         }
 82         build(1, n, 1);
 83         printf("Case %d:\n", i);
 84         while(scanf("%s", str) != EOF)
 85         {
 86             if(!strcmp(str, "End"))
 87             {
 88                 break;
 89             }
 90             int c, d;
 91             scanf("%d%d", &c, &d);
 92             switch(str[0])
 93             {
 94                 case 'A':
 95                     update(c, 1, d);
 96                     break;
 97                 case 'S':
 98                     update(c, 1, -d);
 99                     break;
100                 case 'Q':
101                     printf("%d\n", query(c, d, 1));
102                     break;
103             }
104         }
105     }
106 }
posted @ 2012-09-03 19:15  山路水桥  阅读(176)  评论(0编辑  收藏  举报