Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 51777 | Accepted: 19009 |
Description
Ultra-QuickSort produces the output
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
題意:告訴n個數字,問把他們按照從小到大順序排列好後,需要交換幾次。
使用歸併排序,求一下逆序對的個數就是交換次數,複雜度爲O(nlogn)可以滿足時間限制
#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
using namespace std;
int n;
int a[555555],b[555555];
__int64 ans;
void cpy(int le,int ri)
{
for(int i=le;i<=ri;i++)
a[i]=b[i];
}
void fun(int le,int mid,int ri)
{
int i=le,j=mid+1,k=le;
while(i<=mid && j<=ri)
{
if(a[i]<a[j])
{
b[k++]=a[i];
i++;
}
else
{
b[k++]=a[j];
j++;
ans+=mid-i+1;
}
}
while(i<=mid)
{
b[k++]=a[i];
i++;
}
while(j<=ri)
{
b[k++]=a[j];
j++;
}
}
void merg(int le,int ri)
{
int mid=(ri+le)>>1;
if(le<ri)
{
merg(le,mid);
merg(mid+1,ri);
fun(le,mid,ri);
cpy(le,ri);
}
}
int main()
{
while(~scanf("%d",&n),n)
{
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
ans=0;
merg(1,n);
printf("%I64d\n",ans);
}
return 0;
}