逆序数对的数量(java)
作者:
枫桥夜泊
,
2024-08-06 15:50:49
,
所有人可见
,
阅读 9
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
a[i] = sc.nextInt();
long res = mergesort(a,0,n-1);
System.out.print(res);
}
private static long mergesort(int[] a,int left,int right){
if(left>=right)
return 0;
int mid = (left+right)/2;
long res = mergesort(a,left,mid)+mergesort(a,mid+1,right);
int i = left,j = mid+1,k=0;
int[] q = new int[right-left+1];
while(i<=mid&&j<=right)
{
if(a[i]>a[j])
{
q[k++] = a[j++];
res = res + mid-i+1;
}
else
q[k++] = a[i++];
}
while(i<=mid)
q[k++] = a[i++];
while(j<=right)
q[k++] = a[j++];
for(int c = left,d = 0;c<=right;c++,d++)
a[c] = q[d];
return res;
}
}