[HDOJ1556]Color the ball

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

树状数组的第二类应用:区间更新。需要做的是将update函数修改为由a更新到n+权值即可,然后更新b到n-权值就可以实现固定区间的更新。

代码如下:

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <iostream>
 6 #include <cmath>
 7 #include <queue>
 8 #include <map>
 9 #include <stack>
10 #include <list>
11 #include <vector>
12 
13 using namespace std;
14 
15 const int maxn = 100010;
16 int d[maxn<<1];
17 int n, a, b;
18 
19 //求某点管辖范围
20 int lowbit(int x) { //求x末尾最低位1的位置(末尾0的个数+1)
21     // return x & (x ^ (x - 1));
22     return x & (-x);
23 }
24 
25 //更新树状数组(i到x)
26 void update(int i, int x, int num) {
27     while(i <= x) {    
28         d[i] += num;
29         i += lowbit(i);
30     }
31 }
32 
33 //获取前x项和
34 int getsum(int x) {
35     int sum = 0;
36     while(x > 0) {
37         sum += d[x];
38         x -= lowbit(x);
39     }
40     return sum;
41 }
42 
43 int main() {
44     // freopen("in", "r", stdin);
45     while(~scanf("%d", &n) && n) {
46         memset(d, 0, sizeof(d));
47         for(int i = 1; i <= n; i++) {
48             scanf("%d %d", &a, &b);
49             update(a, n, 1);
50             update(b+1, n, -1);
51         }
52         for(int i = 1; i <= n; i++) {
53             int ans;
54             if(i == 1) {
55                 printf("%d", d[i]);
56             }
57             else {
58                 printf("%d", getsum(i));
59             }
60             if(i != n) {
61                 printf(" ");
62             }
63             else {
64                 printf("
");
65             }
66         }
67     }
68 }
原文地址:https://www.cnblogs.com/kirai/p/4776340.html