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.
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.
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.
Output
For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.
Sample Input
5 9 1 0 5 4 3 1 2 3 0Sample Output
6 0
代码:
树状数组:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
const int N=5e5+5;
long long a[N],c[N];
int n;
int lowbit(int x)
{
return x&-x; //!? !!! &
}
void add(int x,int y)
{
while(x<=n)
{
c[x]+=y;
x=x+lowbit(x);
}
}
long long sum(int x)
{
long long all=0;
while(x>0)
{
all+=c[x];
x=x-lowbit(x);
}
return all;
}
struct TA
{
int val,pos;
bool operator<(const TA& b)//用这个比较快
{
return val<b.val;
}
}poin[N];
//bool cmp(const TA& a,const TA& b) //用这个比较慢
//{
// return a.val<b.val;
//}
int main(void)
{
while(~scanf("%d",&n)&&n)
{
int i;
memset(c,0,sizeof(c));
long long ans=0;
for(i=1;i<=n;i++)
{
scanf("%d",&poin[i].val);
poin[i].pos=i;
}
sort(poin+1,poin+n+1);
for(i=1;i<=n;i++)//离散化?
{
a[poin[i].pos]=i;
}
for(i=1;i<=n;i++)
{
add(a[i],1);
ans+=i-sum(a[i]); //逆序数
}
printf("%lld\n",ans);
}
return 0;
}
归并排序(用时少):
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
long long ans=0;
const int N=5*1e5+10;
int a[N];
void mergearray(int a[],int first,int mid,int last,int temp[])
{
int i=first;
int j=mid+1;
int 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);//逆序数
}
}
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];
}
void merge(int a[],int first,int last,int temp[])
{
if(first<last)
{
int mid=(first+last)>>1;
merge(a,first,mid,temp);
merge(a,mid+1,last,temp);
mergearray(a,first,mid,last,temp);
}
}
void mergesort(int a[],int n)
{
int *p=new int [n+5];
if(p==NULL)
return;
merge(a,0,n-1,p);
delete []p;
}
int main(void)
{
int n;
while(~scanf("%d",&n)&&n)
{
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
ans=0;
mergesort(a,n);
printf("%lld\n",ans);
}
return 0;
}
参考1