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

分治法求逆序对个数(归并排序)

程序员文章站 2022-03-03 07:50:18
...
#include <bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e4;
int n;
int a[maxn], t[maxn];

void read()
{
    cin >> n;
    for(int i = 0; i < n; ++i)
        cin >> a[i];
}

int countReversefewByMergeSort(int arr[], int left, int right, int tempArr[])
{
    int cnt = 0;
    if(left < right)
    {
        int mid = left + (right-left)/2;
        cnt += countReversefewByMergeSort(arr, left, mid, tempArr);
        cnt += countReversefewByMergeSort(arr, mid+1, right, tempArr);
        int i = left, j = mid, k = left;
        while(i < mid || j < right)
        {
            if(j >= right || (i < mid && arr[i] <= arr[j]))
                tempArr[k++] = arr[i++];
            else
            {
                tempArr[k++] = arr[j++];
                cnt += mid-i;
            }
        }
        for(k = left; k < right; ++k)
            arr[k] = tempArr[k];
    }
    return cnt;
}

void solve()
{
    cout << countReversefewByMergeSort(a, 0, n, t);
}

int main()
{
    read();
    solve();
    return 0;
}