Tree Array - There are many trees outside the school gate (nkoj1317)

Tree Array - Lots of trees outside the school gate ( nkoj1317 )

topic analysis

tree array bare question

Convert the problem to a prefix sum solution

This question requires a clever transformation of ??? to become a tree-like array question

Each time you modify the a, b] interval and query the [l, r] interval, you only need to calculate how many [a, b] intervals intersect with the [l, r] interval.

meet

a r , l b

The number of intervals, that is, to find
| { a r } | | { b < l } |

Use tree array to record prefix sum

code

//
// Created by rv on 2018/4/23.
//

#include <cstdio>
#include <cstring>

//const int N = 50000 + 5;

struct BIT {
    int cnt;
    int* s;
    BIT(int n) {
        cnt = n;
        s = new int[n];
        memset(s, 0, sizeof(int) * n);
    }

    void add(int pos, int delta) {
        for (int i = pos; i <= cnt; i += i & -i) {
            s[i] += delta;
        }
    }

    int sum(int pos) {
        int res = 0;
        for (int i = pos; i >= 1; i -= i & -i) {
            res += s[i];
        }
        return res;
    }
};

int main() {
    int n, m, k, l, r;
    scanf("%d%d", &n, &m);
    BIT cnta(n + 1);
    BIT cntb(n + 1);
    while (m--) {
        scanf("%d%d%d", &k, &l, &r);
        if (k == 1) {
            cnta.add(l, 1);
            cntb.add(r, 1);
        } else if (k == 2) {
            printf("%d\n", cnta.sum(r) - cntb.sum(l - 1));
        } else {
            printf("bad scanf\n");
        }
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325753874&siteId=291194637