描述
现在给你一个由n个互不相同的整数组成的序列,现在要求你任意交换相邻的两个数字,使序列成为升序序列,请问最少的交换次数是多少?
输入
输入包含多组测试数据。每组输入第一行是一个正整数n(n<500000),表示序列的长度,当n=0时。
接下来的n行,每行一个整数a[i](0<=a[i]<=999999999),表示序列中第i个元素。
输出
对于每组输入,输出使得所给序列升序的最少交换次数。
输入样例 1
5
9
1
0
5
4
3
1
2
3
0
输出样例 1
6
0
这题可以使用二分归并排序来进行排序,先把数组从中间向两边一分再分,再去回溯即可做到排序,由于数据较多且较大所以建议定义数组时使用long long,由于是相邻的排序所以互换的里面就是+1而是+j-k。
#include <iostream>
using namespace std;
long a[500005],temp[500005],cont;
void megasort(int low,int mid,int high)
{
int i=low;
int j=mid+1;
int k=low;
while(i<=mid&&j<=high)
{
if(a[i]<=a[j])
{
temp[k++]=a[i++];
}
else
{
cont+=j-k;
temp[k++]=a[j++];
}
}
while(i<=mid)
temp[k++]=a[i++];
while(j<=high)
temp[k++]=a[j++];
for(int i=low; i<=high; i++)
{
a[i]=temp[i];
}
}
void mega(int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
mega(low,mid);
mega(mid+1,high);
megasort(low,mid,high);
}
}
int main()
{
int n;
while(cin>>n&&n)
{
cont =0;
for(int i=1; i<=n; i++)
cin>>a[i];
mega(1,n);
cout<<cont<<endl;
}
return 0;
}