Description
In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,
Ultra-QuickSort produces the output
0 1 4 5 9 .
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
【题目分析】
扯了半天,就是求一个逆序对的个数。归并排序解决。
【代码】
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int a[500001];
int b[500001];
long long ans;
int n;
inline void mer(int l,int r)
{
if (l==r) return ;
int mid=(l+r)/2;
mer(l,mid); mer(mid+1,r);
int t1=l,t2=mid+1,t3=l;
while (t3<=r)
{
if (t1>mid) {b[t3++]=a[t2++]; continue;}
if (t2>r) {b[t3++]=a[t1++]; continue;}
if (a[t1]<a[t2]) b[t3++]=a[t1++];
else b[t3++]=a[t2++],ans+=mid-t1+1;
}
for (int i=l;i<=r;++i) a[i]=b[i];
return ;
}
int main()
{
while (scanf("%d",&n)==1&&n)
{
ans=0;
for (int i=1;i<=n;++i) scanf("%d",&a[i]);
mer(1,n);
cout<<ans<<endl;
}
}