欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

归并排序求逆序对

程序员文章站 2022-05-10 15:02:14
...
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 5e5 + 7;
int n; ll cnt;
int a[maxn], b[maxn];
void merg(int L,int M,int R)
{
    int i = L, j = M, k = L;
    while(i < M && j < R)
    {
        if(a[i] > a[j])
        {
            b[k++] = a[j++];
            cnt += M - i;
        }
        else b[k++] = a[i++];
    }
    while(i < M) b[k++] = a[i++];
    while(j < R) b[k++] = a[j++];
    for(i = L; i < R; i++) a[i] = b[i];
}
void MergeSort(int L, int R)
{
    if(L + 1 >= R) return ;
    int M = (L + R) >> 1;
    MergeSort(L, M);
    MergeSort(M, R);
    merg(L, M, R);
}
int main()
{
    cin >> n;
    for(int i = 0; i < n; i++)
        scanf("%d",&a[i]);
    MergeSort(0, n);
    cout << cnt << endl;
    return 0;
}