51Nod - 1019 逆序数 (归并排序)

在一个排列中,如果一对数的前后位置与大小顺序相反,即前面的数大于后面的数,那么它们就称为一个逆序。一个排列中逆序的总数就称为这个排列的逆序数。

如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序数是4。给出一个整数序列,求该序列的逆序数。

Input

第1行:N,N为序列的长度(n <= 50000) 
第2 - N + 1行:序列中的元素(0 <= Aii <= 10^9)

Output

输出逆序数

Sample Input

4
2
4
3
1
扫描二维码关注公众号,回复: 4769392 查看本文章

Sample Output

4

解题思路 :直接暴力枚举会超时,使用归并排序来做,每次归并时求出当前归并序列的逆序数,总的相加就可以了

AC代码:

#include<iostream>
using namespace std;
const int maxn=5e4+10;
int a[maxn];
int ans;
void merge(int a[],int first,int mid,int last,int temp[])//归并 
{//将两个有序序列a[first...mid],a[mid+1...last]合并到temp中 
	int i=first,j=mid+1,k=0;
	while(i<=mid&&j<=last)
	{
		if(a[i]<=a[j])
		{
			temp[k++]=a[i++];
		}
		else
		{
			temp[k++]=a[j++];
			ans+=mid-i+1;
			//因为a[first...mid]时非递减的有序序列,a[i]和a[j]时逆序,则a[i...mid]与a[j]都为逆序,所以总数加mid-i+1;
		}
	}
	while(i<=mid)
		temp[k++]=a[i++];
	while(j<=last)
		temp[k++]=a[j++];
	 for(i=0;i<k;i++)
	 	a[first+i]=temp[i];//排好序重新赋值给a数组 这部分逆序数已经计算过,将其变为有序
}
void mergesort(int a[],int first,int last,int temp[])//排序 
{
	if(first<last)
	{
		int mid=(first+last)/2;
		mergesort(a,first,mid,temp);//左边有序 
		mergesort(a,mid+1,last,temp);//右边有序 
		merge(a,first,mid,last,temp);//将左右两个有序序列排序 
	}
} 
void sort(int a[],int n)//归并排序 
{
	int temp[n];
	mergesort(a,0,n-1,temp);
}
int main()
{
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
		cin>>a[i];
	sort(a,n);
	cout<<ans<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40707370/article/details/85221743
今日推荐