题目描述:
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
输入:
每个测试案例包括两行:
第一行包含一个整数n,表示数组中的元素个数。其中1 <= n <= 10^5。
第二行包含n个整数,每个数组均为int类型。
输出:
对应每个测试案例,输出一个整数,表示数组中的逆序对的总数。
样例输入:
4
7 5 6 4
样例输出:
5
看到这样的题目,最简单的想法就是遍历每一个元素,让其与后面的元素对比,如果大于则count++,但是这样的时间复杂度是o(n2)。这题有更好的解决方法,时间复杂度只需要o(nlogn)。其实这道题目的思路跟归并排序差不多,求逆序对的过程就是一个求归并排序的过程,在求出逆序对以后,原数组变得有序,是通过归并排序得到的。
考虑一下,逆序是说a[i]>a[j],j>i。那么在排序的过程中,会把a[i]和a[j]交换过来,这个交换的过程,每交换一次,就是一个逆序对的“正序”过程。归并排序的思想就是把前一段排序,后一段排序,然后再整体排序。利用归并排序的过程中,在每一次归并两个数组的时候,如果左数组比右数组大,那么着就是一个逆序。记录所有左数组比右数组大的情况,就是全部的逆序数目。
package Test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class jobdu1348 {
static long count = 0;
public static void mergeSort(int []input,int left,int right){
//分治
int mid = (left + right) / 2;
if (left < right) {
// 左边
mergeSort(input,left,mid);
// 右边
mergeSort(input,mid+1,right);
// 左右归并
merge(input,left,mid,right);
}
}
/**
* 二路归并
* @param input
* @param left左数组的第一个元素的索引
* @param center左数组的最后一个元素的索引,center+1是右数组第一个元素的索引
* @param right右数组最后一个元素的索引
*/
public static void merge(int[]input,int left,int center,int right){
int []tempArray = new int[right-left+1];
int mid = center+1;
int temp = left;
int current = 0;
while(left<=center && mid<=right){
if(input[left]>input[mid]){
tempArray[current++]=input[mid++];
/*
* 如果input[left]>input[mid],那么表明下标为left~center的值都会比input[mid]大;
* (5,7,8)(4,9)合并为 3+0+0+0
* */
count+=center-left+1;
}else{
tempArray[current++]=input[left++];
}
}
//只会执行一个
while(left<=center){
tempArray[current++]=input[left++];
}
while(mid<=right){
tempArray[current++]=input[mid++];
}
current=0;
while(temp<=right){
input[temp++]=tempArray[current++];
}
}
public static void main(String[] args) throws IOException {
StreamTokenizer cin = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
while(cin.nextToken()!=cin.TT_EOF){
int n = (int)cin.nval;
int []input = new int[n];
for(int i=0;i<n;i++){
cin.nextToken();
input[i] = (int)cin.nval;
}
count=0;
mergeSort(input,0,input.length-1);
System.out.println(count);
}
}
}