还是一道逆序数的题,再熟悉一下归并排序
import java.util.Scanner;
public class Main {
static int data[] = null;
static long step;
public static void sort(int left,int right,int temp[]){
if(left<right){
int mid = (left+right)/2;
sort(left,mid,temp);
sort(mid+1,right,temp);
merge(left,mid,right,temp);
}
}
public static void merge(int left,int mid,int right,int temp[]){
int i = left;
int j = mid+1;
int t = 0;
while(i<=mid&&j<=right){
if(data[i]<=data[j]){
temp[t++] = data[i++];
}else{
temp[t++] = data[j++];
step+=mid-i+1;
}
}
while(i<=mid){
temp[t++] = data[i++];
}
while(j<=right){
temp[t++] = data[j++];
}
t = 0;
while(left<=right){
data[left++] = temp[t++];
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i = 0;
while(i<n){
int num = sc.nextInt();
data = new int[num];
int j = 0;
while(j<num){
data[j++] = sc.nextInt();
}
int temp[] =new int[num];
step = 0L;
Main.sort(0, num-1, temp);
System.out.println("Scenario #"+(++i)+":");
System.out.println(step);
System.out.println("");
}
}
}