推荐一个今天收获的博客,该博客将归并排序解释地相当清楚,并且有C++语言的实现方法
http://wangkuiwu.github.io/2014/04/28/merge-sort/
主要是解决逆序数对
如题
1007. Inversion Number
题目描述
There is a permutation P with n integers from 1 to n. You have to calculate its inversion number, which is the number of pairs of Pi and Pj satisfying the following conditions: i<j and Pi>Pj.
输入格式
The input may contain several test cases.
In each test case, the first line contains a positive integer n (n<=100000) indicating the number of elements in P. The following n lines contain n integers making the permutation P.
Input is terminated by EOF.
输出格式
For each test case, output a line containing the inversion number.
样例输入
5
3
4
1
5
2
样例输出
5
Problem Source: 期末模拟题C
// Problem#: 13510
// Submission#: 3503240
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std; const int maxn = 1000; long long ans = 0; int A[1000005]; /* 排列两个有序的表 */ void merge(int a[], int start, int mid, int end) { int temp[end-start-1]; int i = start; // 第1个有序区的索引 int j = mid + 1; // 第2个有序区的索引 int k = 0; // 临时区域的索引 while(i <= mid && j <= end) { if(a[i] <= a[j]) temp[k++] = a[i++]; else { temp[k++] = a[j++]; ans += mid - i + 1; } } while(i <= mid) temp[k++] = a[i++]; while(j <= end) temp[k++] = a[j++]; // 将排序后的元素,全部都整合到数组a中。 for (i = 0; i < k; i++) a[start + i] = temp[i]; } /* * 归并排序(从上往下) * * 参数说明: * a -- 待排序的数组 * start -- 数组的起始地址 * endi -- 数组的结束地址 */ void merge_sort_up2down(int a[], int start, int end) { if(a == NULL || start >= end) return; int mid = (start + end) / 2; merge_sort_up2down(a, start, mid); merge_sort_up2down(a, mid+1, end); merge(a, start, mid, end); } int main(){ int n; while (scanf("%d",&n)!=EOF) { ans = 0; int i; for (i=0;i