题目描述
利用归并排序的思路,三部曲
结果用long接收,可能爆int
样例
import java.io.*;
import java.util.Scanner;
/* 2 3 4 1 5 6
三部曲:
1.全在左边
2.全在右边
3.一个在左,一个在右
*/
public class Main {
private static long mergesort(int[] a, int left, int right) {
if (left >= right) {
return 0;
}
int mid = (right + left) / 2;
//全在左边 + 全在右边
long res = mergesort(a, left, mid) + mergesort(a, mid + 1, right);
int i = left;
int j = mid + 1;
int[] temp = new int[right - left + 1];
int k = 0;
//一个在左,一个在右
while (i <= mid && j <= right) {
if (a[i] <= a[j]) {
temp[k++] = a[i++];//不是逆序对就继续存放
} else {
temp[k++] = a[j++];//存放步骤不变
//i右边都是>=本身,所以从大小上都符合逆序对的定义
res += mid - i + 1;//统计逆序对的数量
}
}
while (i <= mid) {
temp[k++] = a[i++];
}
while (j <= right) {
temp[k++] = a[j++];
}
for (i = left, j = 0; i <= right; i++, j++) {
a[i] = temp[j];
}
return res;
}
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
System.out.print(mergesort(arr,0,n-1));
}
}