788. 逆序对的数量
作者:
dsf2
,
2021-03-01 01:08:45
,
所有人可见
,
阅读 458
import java.util.*;
class Main {
static long cnt;
public static void main(String[] args) {
cnt = 0;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = Integer.parseInt(sc.next());
divide(arr);
System.out.println(cnt);
}
public static int[] divide(int[] arr) {
if (arr.length <= 1)
return arr;
int mid = arr.length / 2;
int[] left = new int[mid];
int[] right = new int[arr.length - mid];
int l = 0, r = 0;
for (int i = 0; i < arr.length; i++) {
if (i < mid)
left[l++] = arr[i];
else
right[r++] = arr[i];
}
left = divide(left);
right = divide(right);
int[] sorted = merge(left, right);
return sorted;
}
/**
* arr1 - left arr, arr2 - right arr
*/
public static int[] merge(int[] arr1, int[] arr2) {
int n = arr1.length, m = arr2.length;
int[] newArr = new int[n + m];
int i = 0, j = 0;
int idx = 0;
while (i < n && j < m) {
if (arr1[i] <= arr2[j])
newArr[idx++] = arr1[i++];
else {
cnt += (n - i);
newArr[idx++] = arr2[j++];
}
}
for (; i < n; i++)
newArr[idx++] = arr1[i];
for (; j < m; j++)
newArr[idx++] = arr2[j];
return newArr;
}
}
记得一开始是在算法4看到过的 马住