HDU 1166 敌兵布阵(第一个树状数组)

题目链接

以前用普通方法150+ms 今天看了书上有这个题的详细树状数组的代码,理解下,敲敲交上居然300ms+,我正纳闷的时候,交上以前的代码TLE了。。

 1 #include <stdio.h>
 2 #include <string.h>
 3 #define N 50005
 4 int p[N],n;//p[i] 就代表从i - i&(-i)+1到i的和
 5 int lowbit(int t)//寻找低位起第一个非0位
 6 {
 7     return (-t)&t;//如4二进制是100所以就是4,如7二进制为111,是1
 8 }
 9 void insert(int t,int d)//更新某个点
10 {
11     while(t <= n)
12     {
13         p[t] += d;
14         t += lowbit(t);//要将含有此元素的和都更新
15     }
16 }
17 int getsum(int t)//求和
18 {
19     int sum = 0;
20     while(t > 0)
21     {
22         sum += p[t];
23         t -= lowbit(t);
24     }
25     return sum;
26 }
27 int main()
28 {
29     int t,i,num = 0,x,y,k;
30     char str[100];
31     scanf("%d",&t);
32     while(t--)
33     {
34         num ++;
35         memset(p,0,sizeof(p));
36         scanf("%d",&n);
37         for(i = 1;i <= n;i ++)
38         {
39             scanf("%d%*c",&k);
40             insert(i,k);
41         }
42         scanf("%s",str);
43         printf("Case %d:\n",num);
44         while(strcmp(str,"End") != 0)
45         {
46             scanf("%d%d%*c",&x,&y);
47             if(strcmp(str,"Query") == 0)
48             printf("%d\n",getsum(y)-getsum(x-1));
49             else if(strcmp(str,"Add") == 0)
50             insert(x,y);
51             else if(strcmp(str,"Sub") == 0)
52             insert(x,(-1)*y);
53             scanf("%s",str);
54         }
55     }
56     return 0;
57 }
posted @ 2012-07-17 10:20  Naix_x  阅读(165)  评论(0编辑  收藏  举报