在分治后的每一层合并中顺便求出逆序对数量是这个题想法的由来,归并排序分治我们求的是从小到大的顺序,我们所求的逆序对恰好是逆序数量,与归并排序不谋而合。
例如[3,4,1,2]中q[0]>q[2],则q[0],q[1]都与q[2]成逆序对,而q[mid]与q[i]有mid-i+1个数字,因此逆序对增加mid-i+1
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 100010, n;
static int a[] = new int[N], tmp[] = new int[N];
public static void main(String[] args) throws NumberFormatException, IOException {
n = Integer.parseInt(br.readLine());
String s[] = br.readLine().split(" ");
for (int i = 0; i < n; i++) a[i] = Integer.parseInt(s[i]);
pw.print(merge_sort(0, n - 1));
pw.flush();
pw.close();
br.close();
}
public static long merge_sort(int l, int r) {
if (l >= r) return 0;
int mid = l + r >> 1;
long res = merge_sort(l, mid) + merge_sort(mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r) {
if (a[i] <= a[j]) tmp[k++] = a[i++];
else {
tmp[k++] = a[j++];
res += mid - i + 1;
}
}
while (i <= mid) tmp[k++] = a[i++];
while (j <= r) tmp[k++] = a[j++];
for (i = l, j = 0; i <= r; i++, j++) a[i] = tmp[j];
return res;
}
}