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

求逆序对

时间:2020-06-10 17:20:34      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:tor   bool   sort   +=   sum   return   scanf   turn   code   

归并排序

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\n", ans);
}

求逆序对

标签:tor   bool   sort   +=   sum   return   scanf   turn   code   

原文地址:https://www.cnblogs.com/Accpted/p/13086552.html

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