树状数组入门 之 hdu 1166

树状数组与线段树实现
本文介绍了一种使用树状数组解决特定问题的方法,并提供了详细的代码实现。此外,还对比了线段树的解决方案,帮助读者理解两种数据结构在处理区间查询和更新操作时的应用场景。

第一道树状数组。。。入门。。。线段树做法:代码见这里

 1 //  [4/7/2014 Sjm]
 2 #include <iostream>
 3 #include <cstdio>
 4 #include <cstdlib>
 5 #include <string>
 6 using namespace std;
 7 const int MAX_N = 50000;
 8 int bit[MAX_N + 1], n;
 9 
10 int mySum(int i)
11 {
12     int sum = 0;
13     while (i>0){
14         sum += bit[i];
15         i -= (i&(-i));
16     }
17     return sum;
18 }
19 
20 void myAdd(int i, int x)
21 {
22     while (i<=n) {
23         bit[i] += x;
24         i += (i&(-i));
25     }
26 }
27 
28 int main()
29 {
30     //freopen("input.txt", "r", stdin);
31     //freopen("output.txt", "w", stdout);
32     int T;
33     scanf("%d", &T);
34     for (int i = 1; i <= T; i++)
35     {
36         memset(bit, 0, sizeof(bit));
37         printf("Case %d:\n", i);
38         scanf("%d", &n);
39         for (int j = 1; j <= n; j++) {
40             int x;
41             scanf("%d", &x);
42             myAdd(j, x);
43         }
44         string str;
45         while (cin>>str && ('E' != str[0]))
46         {
47             int a, b;
48             scanf("%d %d", &a, &b);
49             if ('Q' == str[0])
50                 printf("%d\n", mySum(b) - mySum(a-1));
51             else {
52                 if ('A' == str[0]) myAdd(a, b);
53                 else myAdd(a, -b);
54             }
55         }
56     }
57     return 0;
58 }

转载于:https://www.cnblogs.com/shijianming/p/4140861.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值