模板

这东西确实没有线段树方便用,经常要倒转区间。奈何速度过于惊人。

某一场CF上要求的二维偏序的问题,注意离散化的时候有时候要-1。

一定要注意树状数组的add中,传的不是n,而是离散化后坐标的xtop。

而且要注意在离散化的时候,unique后求元素的个数时用-(x+1),lower_bound求元素偏移时用-x。

int n;
int a[200005];
int b[200005];
int x[400005], xtop;
int bit[400005];
 
void add(int x, int v) {
    for(; x <= xtop; x += x & (-x))
        bit[x] += v;
}
 
ll sum(int x) {
    ll res = 0;
    for(; x; x -= x & (-x))
        res += bit[x];
    return res;
}
 
void test_case() {
    scanf("%d", &n);
    for(int i = 1; i <= n; ++i)
        scanf("%d", &a[i]);
    xtop = 0;
    for(int i = 1; i <= n; ++i) {
        scanf("%d", &b[i]);
        x[++xtop] = a[i] - b[i] - 1;
        x[++xtop] = b[i] - a[i];
    }
    sort(x + 1, x + 1 + xtop);
    xtop = unique(x + 1, x + 1 + xtop) - (x + 1);
    ll ans = 0;
    for(int i = 1; i <= n; ++i) {
        int pos1 = lower_bound(x + 1, x + 1 + xtop, a[i] - b[i] - 1) - x;
        ans += sum(pos1);
        int pos2 = lower_bound(x + 1, x + 1 + xtop, b[i] - a[i]) - x;
        add(pos2, 1);
    }
    printf("%lld
", ans);
}
原文地址:https://www.cnblogs.com/KisekiPurin2019/p/12484177.html