逆序数

归并的思想

有一种排序的方法是归并排序,归并排序的主要思想是将整个序列分成两部分,分别递归将这两部分排好序之后,再和并为一个有序的序列,核心代码如下

MergeSort(first,last)

{

If(first>=last)

return

Int med=(first+last)/2;

MergeSort(first,med);

MergeSort(med+1,last);

Merge(first,last);

}

在合并的过程中是将两个相邻并且有序的序列合并成一个有序序列,如以下两个有序序列

Seq13  4  5

Seq22  6  8  9

合并成一个有序序:

Seq2  3  4  5  6  8  9

对于序列seq1中的某个数a[i],序列seq2中的某个数a[j],如果a[i]<a[j],没有逆序数,如果a[i]>a[j],那么逆序数为seq1a[i]后边元素的个数(包括a[i]),即len1-i+1,

这样累加每次递归过程的逆序数,在完成整个递归过程之后,最后的累加和就是逆序的总数



#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cmath>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
#define esp  1e-8
const double PI = acos(-1.0);
const double e = 2.718281828459;
const int inf = 1000000005;
const long long mod = 1000000009;
//freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
//freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中ci
int  a[50005], temp[50005];
int ans;
void Merge(int L, int m, int R)
{
	int tot = 1;
	int i = L;
	int j = m + 1;
	while (i <= m && j <= R)
	{
		if (a[i] < a[j])
		{
			temp[tot++] = a[i++];
		}
		else
		{
			temp[tot++] = a[j++];
			ans += m - i + 1;
		}
	}
	while (i <= m)
		temp[tot++] = a[i++];
	while (j <= R)
		temp[tot++] = a[j++];
	for (int k = 1; k < tot; ++k)
		a[L++] = temp[k];
}
void mergesort(int L, int R)
{
	if (L >= R)
		return;
	int m = (L + R) / 2;
	mergesort(L, m);
	mergesort(m + 1, R);
	Merge(L, m, R);
}
int main()
{
	int n;
	while (~scanf("%d", &n))
	{
		for (int i = 1; i <= n; ++i)
			scanf("%d", &a[i]);
		ans = 0;
		mergesort(1, n);
		printf("%d\n", ans);
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值