其他分享
首页 > 其他分享> > 归并排序求逆序对

归并排序求逆序对

作者:互联网

 

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
using namespace std;
int n, a[100010], tmp[100010];
long long ans;
void msort(int left, int right) 
{ if (left == right)return; int mid = (left + right) / 2; msort(left, mid); msort(mid + 1, right); int i = left, j = mid + 1, k = 0; while (i <= mid && j <= right) { if (a[i] < a[j]) tmp[++k] = a[i], i++; else tmp[++k] = a[j], j++, ans += mid - i + 1; } while (i <= mid) tmp[++k] = a[i++]; while (j <= right) tmp[++k] = a[j++]; for (int i = 1; i <= k; i++) a[left + i - 1] = tmp[i]; } int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; msort(1, n); cout << ans; }

 

两份其实差不多,下面的好看一点qwq

 

#include <bits/stdc++.h>

const int N = 1e5 + 9;
int n, a[N], b[N];

typedef long long lld;
lld c1, c2;

void msort(int lef, int rig) {
    if (lef == rig)
        return;

    int mid = lef + rig >> 1;
    msort(lef, mid);
    msort(mid + 1, rig);

    int tmp[rig - lef], i = lef, j = mid + 1, k = 0;
    while (i <= mid && j <= rig) {
        if (a[i] < a[j])
            tmp[k++] = a[i++];
        else {
            c1 += mid + 1 - i;
            tmp[k++] = a[j++];
        }
    }
    while (i <= mid) tmp[k++] = a[i++];
    while (j <= rig) tmp[k++] = a[j++];

    k = 0;
    while (lef <= rig) a[lef++] = tmp[k++];
}

int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d", a + i);
        b[i] = a[i];
    }

    msort(0, n - 1);

    printf("%lld\n", c1);
}

 

标签:归并,include,lef,int,mid,msort,rig,排序,逆序
来源: https://www.cnblogs.com/phemiku/p/11406038.html