【hihocoder】三十九周:二分.归并排序之逆序对
2015-04-02 10:01
330 查看
就是用归并排序求数组中得逆序对。假设数组为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型防止溢出。
View Code
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型防止溢出。
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] arr = new int ; for(int i = 0;i < n;i++) arr[i] = in.nextInt(); MergeSort(arr,0,arr.length-1); /* for(int i = 0;i < arr.length;i++) System.out.print(arr[i]); */ System.out.print(total); } private static void MergeSort(int[] arr,int begin,int end){ if(begin >= end) return; int mid = (begin+end)/2; MergeSort(arr, begin, mid); MergeSort(arr, mid+1, end); merge(arr, begin, end); } public static long total = 0; private static void merge(int[] arr,int begin,int end){ int belement = 0; int mid = (begin+end)/2; int p1 = begin; int p2 = mid+1; int count = 0; int[] sorted = new int[end-begin+1]; while(p1 <= mid && p2 <= end){ if(arr[p1] > arr[p2]){ sorted[count] = arr[p2]; p2++; count++; belement++; //System.out.println(belement); }else{ total += belement; sorted[count] = arr[p1]; p1++; count++; } } while(p1 <= mid){ sorted[count] = arr[p1]; count++; p1 ++; total += belement; } while(p2 <= end){ sorted[count] = arr[p2]; count ++; p2++; } for(int i = begin;i <= end;i++) arr[i] = sorted[i-begin]; } }
View Code
相关文章推荐
- HiHoCoder-第三十九周--二分·归并排序之逆序对
- hihoCoder 1141 二分·归并排序之逆序对
- hihoCoder_二分·归并排序之逆序对
- #1141 : 二分·归并排序之逆序对(归并排序)
- hiho一下 第三十九周 #1141 : 二分·归并排序之逆序对 【归并排序----树状数组】
- hihocoder #1141 : 二分·归并排序之逆序对
- 【hiho39】二分·归并排序之逆序对
- 【hihocoder】二分·归并排序之逆序对
- 从逆序对问题展开 归并排序习题归纳
- 归并排序求逆序对
- 数据结构实验之排序五:归并求逆序数
- 数据结构实验之排序五:归并求逆序数
- C++数据结构 排序 二分 插入 冒泡 基数 归并 直选 快排 希尔 堆排序
- sdut oj3402 数据结构实验之排序五:归并求逆序数
- 数据结构实验之排序五:归并求逆序数
- hihoCoder#1141 二分·归并排序之逆序对
- 数据结构实验之排序五:归并求逆序数
- 利用归并排序思想求数组中的逆序对
- 数据结构实验之排序五:归并求逆序数【归并排序】
- 【NOI导刊】【归并排序求逆序对】最接近神的人