九度oj 1348 数组中的逆序对

时间:2023-03-09 15:53:15
九度oj 1348 数组中的逆序对

原题链接:http://ac.jobdu.com/problem.php?pid=1348 
归并排序求逆序对。。。

 #include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
typedef unsigned long long ull;
const int Max_N = ;
ull res;
int arr[Max_N], temp[Max_N];
void Merge(int *A, int l, int m, int r) {
int p = ;
int x = l, y = m + ;
while (x <= m && y <= r) {
if (A[x] > A[y]) res += m - x + , temp[p++] = A[y++];
else temp[p++] = A[x++];
}
while (x <= m) temp[p++] = A[x++];
while (y <= r) temp[p++] = A[y++];
for (x = ; x < p; x++) A[l + x] = temp[x];
}
void MergeSort(int *A, int l, int r) {
int mid;
if (l < r) {
mid = (l + r) >> ;
MergeSort(A, l, mid);
MergeSort(A, mid + , r);
Merge(A, l, mid, r);
}
}
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w+", stdout);
#endif
int n;
while (~scanf("%d", &n)) {
res = ;
for (int i = ; i < n; i++) scanf("%d", &arr[i]);
MergeSort(arr, , n - );
printf("%lld\n", res);
}
return ;
}