12 逆序数

 利用归并排序求解

归并排序的主要思想是将整个序列分成两部分,分别递归将这两部分排好序之后,再和并为一个有序的序列。

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

Seq1:3  4  5

Seq2:2  6  8  9

合并成一个有序序:

Seq:2  3  4  5  6  8  9

对于序列seq1中的某个数a[i],序列seq2中的某个数a[j],如果a[i]<a[j],没有逆序数,如果a[i]>a[j],那么逆序数为seq1中a[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);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/C_CQQ/article/details/81224308