#include<iostream>
#include<vector>
using namespace std;
int ans = 0;
//归并+排序
void MergeSort(vector<int>& a, int l, int mid, int r) {
int* tmp = new int[r - l + 1];
int i = l, j = mid + 1, index=0;
while (i <= mid && j <= r) {
if (a[i] <= a[j]) {
tmp[index++] = a[i++];
}
else { //a[i]>a[j]
tmp[index++] = a[j++];
ans += mid - i + 1;
}
}
while (i <= mid)tmp[index++] = a[i++];
while (j <= r) tmp[index++] = a[j++];
for (int i = 0; i < index; i++) {
a[l + i] = tmp[i];
}
delete[]tmp;
}
//递归分解+合并+排序
void Merge_up2down(vector<int>& a,int l,int r) {
if (l >= r)return;
int mid = (l + r) / 2;
Merge_up2down(a, l, mid);
Merge_up2down(a, mid + 1, r);
MergeSort(a, l, mid, r);
}
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)cin >> a[i];
Merge_up2down(a, 0, a.size() - 1);
//for (auto i : a)cout << i << ' ';
cout << ans;
return 0;
}
求逆序对 归并O(nlongn)
最新推荐文章于 2024-11-14 21:21:03 发布