利用归并排序求逆序数对
先推荐一个博客,该博客很好地解释了归并排序
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
这个题目其实就是求逆序数对的个数,一开始可以考虑到用冒泡排序的思想求解,两层循环来判断逆序数对的个数,但是显然会超时,所以考虑用归并排序的思想,而且归并排序的时间复杂度要低很多,绝对不会超时。
#include <iostream>
#include <stack>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <cstring>
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 = (int *)malloc((end - start + 1)*sizeof(int));
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<n; i++)
scanf("%d", &A[i]);
merge_sort_up2down(A, 0, n - 1);
printf("%lld\n", ans);
}
}