利用归并排序求逆序数对

利用归并排序求逆序数对

先推荐一个博客,该博客很好地解释了归并排序

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);
	}
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值