求逆序对

Posted accpted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了求逆序对相关的知识,希望对你有一定的参考价值。

归并排序

void merge_sort(int l,int r) {
    if (l == r) {
        return;
    }
    int mid = l + r >> 1;
    merge_sort(l, mid);
    merge_sort(mid + 1, r);
    int i = l, j = mid + 1, k = l;
    while (i <= mid && j <= r) {
        if (a[i] <= a[j]) {
            b[k++] = a[i++];
        } else {
            ans += mid - i + 1;
            b[k++] = a[j++];
        }
    }
    while (i <= mid) {
        b[k++] = a[i++];
    }r
    while (j <= r) {
        b[k++] = a[j++];
    }
    for (int i = l; i <= r; i++) {
        a[i] = b[i];
    }
}

树状数组

struct Node {
    int x, y;

    bool operator<(const Node &b) const {
        return x < b.x;
    }
}a[N];
int n;
int lowbit(int x) {
    return x & -x;
}
void add(int x,int d) {
    for (int i = x; i <= n; i += lowbit(i)) {
        b[i] += d;
    }
}
int sum(int x) {
    int res = 0;
    for (int i = x; i; i -= lowbit(i)) {
        res += b[i];
    }
    return res;
}
int main() {
    scanf("%d", &n);
    for (int = 1; i <= n; i++) {
        scanf("%d", a[i].x);
        a[i].y = i;
    }
    sort(a + 1, a + 1 + n);
    for (int i = 1; i <= n; i++) {
        add(a[i].y, 1);
        ans += i - sum(a[i].y);
    }
    printf("%d
", ans);
}

以上是关于求逆序对的主要内容,如果未能解决你的问题,请参考以下文章

树状数组求逆序对

归并排序求逆序对

归并排序求逆序对

线段树求逆序对

一道编程题:求逆序对的个数

Another Version of Inversion 二维树状数组求逆序对