[HZOI 2016] 偏序(CDQ套CDQ)

传送门

思路:
就是cdq套cdq的模板题

#include 
using namespace std;
typedef long long ll;
const int N = 100005;

struct node {
    int d1, d2, d3, d4, part;
}a[N], b[N], d[N];
int n, ans;

int c[N];

int lowbit(int x) {return x & (-x);}

void add(int x, int v) {
    for(; x < N; x += lowbit(x)) c[x] += v;
}

int query(int x) {
    int ans = 0;
    for(; x; x -= lowbit(x)) ans += c[x];
    return ans;
}

void cdq2(int l, int r) {
    if(l == r) return ;
    int mid = (l + r) >> 1;
    cdq2(l, mid); cdq2(mid + 1, r);
    int t1 = l, t2 = mid + 1;
    for(int i = l; i <= r; i++) {
        if(t2 > r || (t1 <= mid && b[t1].d3 < b[t2].d3)) {
            if(b[t1].part == 0) add(b[t1].d4, 1);
            d[i] = b[t1++];
        } else {
            if(b[t2].part == 1) ans += query(b[t2].d4);
            d[i] = b[t2++];
        }
    }
    for(int i = l; i <= mid; i++) {
        if(b[i].part == 0) add(b[i].d4, -1);
    }
    for(int i = l; i <= r; i++) b[i] = d[i];
}

void cdq(int l, int r) {
    if(l == r) return;
    int mid = (l + r) >> 1;
    cdq(l, mid); cdq(mid + 1, r);
    int t1 = l, t2 = mid + 1;
    for(int i = l; i <= r; i++) {
        if(t2 > r || (t1 <= mid && a[t1].d2 < a[t2].d2)) {
            a[t1].part = 0;
            b[i] = a[t1++];
        } else {
            a[t2].part = 1;
            b[i] = a[t2++];
        }
    }
    for(int i = l; i <= r; i++) a[i] = b[i];
    cdq2(l, r);
}

int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i++) {
        a[i].d1 = i;
        cin >> a[i].d2;
    }
    for(int i = 1; i <= n; i++) cin >> a[i].d3;
    for(int i = 1; i <= n; i++) cin >> a[i].d4;
    cdq(1, n);
    cout << ans;
    return 0;
}

转载于:https://www.cnblogs.com/heyuhhh/p/11493661.html

你可能感兴趣的:([HZOI 2016] 偏序(CDQ套CDQ))