Loading

归并排序 --分治

复杂度O(NlogN)

求逆序对:

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
#include<queue>
#include<deque>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<stack>
#include<cctype>
const double PI = acos(-1.0);
#define eps 1e-6
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;

const int maxn = 5000010;
int n;
int a[maxn], c[maxn];
ll ans;   //存储逆序对个数
 

//归并排序,分而治之
void msort(int l, int r) {
    if (l == r) return;
    int mid = l + r >> 1;
    int i = l, j = mid + 1, k = l;
    msort(l, mid);
    msort(mid + 1, r);
    while (i <= mid && j <= r) {
        if (a[i] <= a[j]) c[k++] = a[i++];
        else c[k++] = a[j++], ans += mid - i + 1;
    }
    while (i <= mid) {
        c[k++] = a[i++];
    }
    while (j <= r) {
        c[k++] = a[j++];
    }
    for (int h = l; h <= r; h++) {
        a[h] = c[h];
    }
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <=n; i++) scanf("%d", &a[i]);
    msort(1, n);
    printf("%lld", ans);
    return 0;    
}

 

posted @ 2020-02-12 18:08  MQFLLY  阅读(97)  评论(0编辑  收藏  举报