HDU 1556树状数组

传送门: HDU 1556

题解

树状数组模板题
区间染色 + 统计次数
向上查询, 向下统计
先把a之后的区间加一次染色更新, 再把b之后减一次染色更新, 这样[a, b]데染色更新就完成了


AC code:

#include
#include
#include
using namespace std;

#define lowbit(x) (x & (-x))
#define LL long long 
#define debug 1

const int maxn(100005);
const int mod(1e9 + 7);

int c[maxn];

int n;



void add(int x, int y, int v) {

    for (int i = x; i <= n; i += lowbit(i)) {
        c[i] += v;
    }

    for (int i = y + 1; i <= n; i += lowbit(i)) {
        c[i] -= v;
    }
}

int getSum(int x) {
    int res = 0;

    for (int i = x; i; i -= lowbit(i)) {
        res += c[i];
    }

    return res;
}

int main() {
#if debug
    freopen("in.txt", "r", stdin);
#endif //debug

    int a, b;

    while (cin >> n, n) {

        memset(c, 0, sizeof(c));

        for (int i = 1; i <= n; ++i) {
            cin >> a >> b;
            add(a, b, 1);
        }

        for (int i = 1; i <= n; i++) {
            int ans = getSum(i);
            cout << ans << (i == n ? "\n" : " ");
        }
    }

    return 0;
}

你可能感兴趣的:(HDU,数据结构-树状数组)