【hihocoder】三十九周:二分.归并排序之逆序对

就是用归并排序求数组中得逆序对。假设数组为a:[2 4 5],和b:[1 3],那么在这一次归并的时候逆序对这样求,belement表示当前result数组中b数组对应的元素个数,total表示逆序对的个数:

a:[2 4 5]  b:[1 3]   result{}

a:[2 4 5]  b[3]       result{1}              belement = 1;

a:[4 5]  b[3]          result{1 2}           belement = 1;        total = total + belement = 1;

a:[4 5]  b[]          result{1 2 3}        belement = 2;        total = 1;

a:[5]  b[]               result{1 2 3 4}     belement = 2;        total = total + belement = 3

a:[]  b[]                 result{1 2 3 4 5}  belement = 2;        total = total + belement = 5

所以数组2 4 5 1 3的逆序数总共有5个。

JAVA版本代码如下:注意total要设置成long型防止溢出。

 1 import java.util.Scanner;
 2 public class Main {
 3 
 4     public static void main(String[] args) {
 5         // TODO Auto-generated method stub
 6         
 7         Scanner in = new Scanner(System.in);
 8         int n = in.nextInt();
 9         int[] arr = new int[n];
10         for(int i = 0;i < n;i++)
11             arr[i] = in.nextInt();
12         MergeSort(arr,0,arr.length-1);
13         /*
14         for(int i = 0;i < arr.length;i++)
15             System.out.print(arr[i]);
16             */
17         System.out.print(total);
18     }
19     private static void MergeSort(int[] arr,int begin,int end){
20         if(begin >= end)
21             return;
22         int mid = (begin+end)/2;
23         MergeSort(arr, begin, mid);
24         MergeSort(arr, mid+1, end);
25         merge(arr, begin, end);
26     }
27     public static long total = 0;
28     private static void merge(int[] arr,int begin,int end){
29         int belement = 0;
30         int mid = (begin+end)/2;
31         int p1 = begin;
32         int p2 = mid+1;
33         int count = 0;
34         int[] sorted = new int[end-begin+1];
35         
36         while(p1 <= mid && p2 <= end){
37             if(arr[p1] > arr[p2]){
38                 sorted[count] = arr[p2];
39                 p2++;
40                 count++;
41                 belement++;        
42                 //System.out.println(belement);
43             }else{
44                 total += belement;
45                 sorted[count] = arr[p1];
46                 p1++;
47                 count++;
48             }
49         }
50         
51         while(p1 <= mid){
52             sorted[count] = arr[p1];
53             count++;
54             p1 ++;
55             total += belement;
56         }
57         
58         while(p2 <= end){
59             sorted[count] = arr[p2];
60             count ++;
61             p2++;
62         }
63         
64         for(int i = begin;i <= end;i++)
65             arr[i] = sorted[i-begin];
66     }
67     
68 }
View Code

 

posted @ 2015-04-02 10:01  SunshineAtNoon  阅读(148)  评论(0编辑  收藏  举报