码迷,mamicode.com
首页 > 其他好文 > 详细

「CQOI2011」动态逆序对

时间:2020-01-24 00:28:56      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:pen   元素   com   har   维护   pre   query   amp   read   

「CQOI2011」动态逆序对

传送门
树套树。
删除一个位置的元素带来的减损数等于他前面大于它的和后面小于它的,然后这个直接树状数组套主席树维护一下就好了。
参考代码:

#include <cstdio>
#define rg register
#define file(x) freopen(x".in", "r", stdin), freopen(x".out", "w", stdout)
template < class T > inline void read(T& s) {
    s = 0; int f = 0; char c = getchar();
    while ('0' > c || c > '9') f |= c == '-', c = getchar();
    while ('0' <= c && c <= '9') s = s * 10 + c - 48, c = getchar();
    s = f ? -s : s;
}

typedef long long LL;
const int _ = 1e5 + 5, __ = 1e7 + 5;

int n, q, a[_], pos[_];
int tot, rt[_], lc[__], rc[__], t1[_], t2[_]; LL cnt[__];

inline void update(int& p, int x, int v, int l = 1, int r = n) {
    if (!p) p = ++tot; cnt[p] += v;
    if (l == r) return ;
    int mid = (l + r) >> 1;
    if (x <= mid) update(lc[p], x, v, l, mid);
    else update(rc[p], x, v, mid + 1, r);
}

inline LL Query(int l, int r, int x, int opt) {
    int c1 = 0, c2 = 0; --l;
    for (rg int i = l; i >= 1; i -= i & -i) t1[++c1] = rt[i];
    for (rg int i = r; i >= 1; i -= i & -i) t2[++c2] = rt[i];
    l = 1, r = n;
    LL res = 0;
    while (l < r) {
        int mid = (l + r) >> 1;
        if (x <= mid) {
            if (opt == 0) {
                for (rg int i = 1; i <= c1; ++i) res -= cnt[rc[t1[i]]];
                for (rg int i = 1; i <= c2; ++i) res += cnt[rc[t2[i]]];
            }
            for (rg int i = 1; i <= c1; ++i) t1[i] = lc[t1[i]];
            for (rg int i = 1; i <= c2; ++i) t2[i] = lc[t2[i]];
            r = mid;
        } else {
            if (opt == 1) {
                for (rg int i = 1; i <= c1; ++i) res -= cnt[lc[t1[i]]];
                for (rg int i = 1; i <= c2; ++i) res += cnt[lc[t2[i]]];             
            }
            for (rg int i = 1; i <= c1; ++i) t1[i] = rc[t1[i]];
            for (rg int i = 1; i <= c2; ++i) t2[i] = rc[t2[i]];         
            l = mid + 1;
        }
    }
    return res;
}

int main() {
    read(n), read(q);
    LL ans = 0;
    for (rg int i = 1; i <= n; ++i) {
        read(a[i]), pos[a[i]] = i;
        ans += Query(1, i - 1, a[i], 0);
        for (rg int j = i; j <= n; j += j & -j) update(rt[j], a[i], 1);
    }
    for (rg int x; q--; ) {
        printf("%lld\n", ans);
        read(x);
        ans -= Query(1, pos[x] - 1, x, 0);
        ans -= Query(pos[x] + 1, n, x, 1);
        for (rg int j = pos[x]; j <= n; j += j & -j) update(rt[j], x, -1);
    }
    return 0;
}

「CQOI2011」动态逆序对

标签:pen   元素   com   har   维护   pre   query   amp   read   

原文地址:https://www.cnblogs.com/zsbzsb/p/12231671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!