16.Swaps, swaps, everywhere

Suppose you have invented a sorting algorithm that sorts the given numbers in acending order. The method of your algorithm is pretty simple: select two adjacent numbers and swap their positions until the number sequence is sorted.

Now you want to examine your algorithm analytically. You want to find out the minimum number of swaps your algorithm will perform on a given sequence. Please write a program to do this job automatically.

For example, your algorithm may perform 5 swaps at least on sequence 5, 1, 2, 4, 3. Here’s the process:

5,1,2,4,3 —(swaps 5 with 1)—> 1,5,2,4,3 —(swaps 5 with 2)—> 1,2,5,4,3 —(swaps 5 with 4)—> 1,2,4,5,3 —(swaps 5 with 3)—> 1,2,4,3,5 —(swaps 4 with 3)—> 1,2,3,4,5 (DONE).

Input

The input file contains multiple test cases. Please process to the end of file.

The first line of each test cases contains a single integer N (1 <= N <= 500,000), indicating the quantity of numbers in the original sequence to be sorted. The next line contains N space-separated integers indicating the sequence itself. All numbers in the sequence is between 0 and 1’000’000’000, inclusive. It is guaranteed that the sum of N among all test cases in the input file will not exceed 2’000’000.

Output

For each test case, your program should generate a single line of output containing the minimum number of swaps your algorithm will perform on the given sequence.

测试用例
in:
5
5 1 2 4 3
3
1 2 3
out:
5↵
0↵

归并排序求逆序,不解释太多。

#include<stdio.h>
#include<stdlib.h>
#define max 500005
long long count;
int r1[max],a[max];
void Merge(int r[],int r1[],int s,int m,int t)
{
	int i=s,j=m+1,k=s;
	while(i<=m&&j<=t)
	{
		if(r[i]<=r[j])
		   r1[k++]=r[i++];
		else
		{
		   r1[k++]=r[j++];
		   count+=(m-i+1);
		}
	}
	while(i<=m)
	   r1[k++]=r[i++];
	while(j<=t)
	   r1[k++]=r[j++];
	for(i=s;i<=t;i++)
	   r[i]=r1[i];
}
int MergeSort(int r[],int s,int t)
{
	int m;
	if(s==t)
	   return -1;
	else
	{
		m=(s+t)/2;
		MergeSort(r,s,m);
		MergeSort(r,m+1,t);
		Merge(r,r1,s,m,t);
	}
}
int main()
{
    int n,i;
    while(~scanf("%d",&n))
    {
    	count=0;
	    for(i=0;i<n;i++)
	       scanf("%lld",&a[i]);
	    MergeSort(a,0,n-1);
	    printf("%lld\n",count);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ArgentumHook/article/details/83054809
今日推荐