题目链接:https://www.acwing.com/problem/content/790/
解法:
主要的问题集中在第22行的处理,记住一个原则:谁流失,统计谁!一旦j++,那么arr[j]将不可能被统计到,所以应该统计所有大于arr[j]的右边的数
AC代码:
import java.util.*;
public class Main {
static int N = (int) 1e5 + 10;
static int[] arr = new int[N], t = new int[N];
static long mergeCount(int[] arr, int l, int r) {
if (l >= r) return 0;
long res = 0;
int mid = l + r >> 1;
res += mergeCount(arr, l, mid);
res += mergeCount(arr, mid + 1, r);
int i = l, j = mid + 1;
int pos = 0;
while (i <= mid && j <= r) {
if (arr[i] <= arr[j]) t[pos ++] = arr[i ++];
else {
res += mid - i + 1;
t[pos ++] = arr[j ++];
}
}
while (i <= mid) {
t[pos ++] = arr[i ++];
}
while (j <= r) {
t[pos ++] = arr[j ++];
}
for (int k = 0; k < pos; k ++) arr[l + k] = t[k];
return res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i ++) arr[i] = sc.nextInt();
long res = mergeCount(arr, 0, n - 1);
System.out.println(res);
}
}