Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 70907 | Accepted: 26628 |
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.
Input
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 0
Sample Output
6 0
题意:求一个序列的逆序数。
逆序数:如 3 6 5 2 7 4从下标为0的数开始小于编号0的数中比3大的数为0个,小于编号为1的数中比6大的数为0个,比5大的数有1个,比2大的数有3个,比7大的数有0个,比4大的数有3个。
即: 0 0 1 3 0 3
则该序列的逆序数为0+0+1+3+0+3=7。
这道题有多种做法,我们这里介绍两种:
1、归并排序法求逆序数:
#include<iostream>
#define ll long long
using namespace std;
ll cnt;
int arr[500005],aux[500005];
void merges(int arr[],int l,int mid,int r)
{
for(int m=l;m<=r;m++)
aux[m-l]=arr[m];
int i=l,j=mid+1;
for(int k=l;k<=r;k++)
{
if(i>mid){
arr[k]=aux[j-l];
j++;
}
else if(j>r){
arr[k]=aux[i-l];
i++;
}
else if(aux[i-l]<aux[j-l]){
arr[k]=aux[i-l];
i++;
}
else {
arr[k]=aux[j-l];
j++;
cnt+=mid-i+1;
}
}
return ;
}
void merge_sort(int arr[],int l,int r)
{
if(l<r){
int mid=(l+r)/2;
merge_sort(arr,l,mid);
merge_sort(arr,mid+1,r);
merges(arr,l,mid,r);
}
return ;
}
int main()
{
int n;
while(cin>>n)
{
cnt=0;
if(n==0)break;
for(int i=0;i<n;i++)
cin>>arr[i];
merge_sort(arr,0,n-1);
cout<<cnt<<endl;
}
return 0;
}
2、树状数组求逆序数:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
int n;
struct node
{
int v,x;
} a[500005];
bool cmp(node a,node b)
{
return a.v<b.v;
}
int t[500005];
int s[500005];
int lowbit(int n)
{
return n&(-n);
}
void modify(int x,int y)
{
while(x<=n)
{
s[x]+=y;
x+=lowbit(x);
}
}
int query(int x)
{
int sum=0;
while(x)
{
sum+=s[x];
x-=lowbit(x);
}
return sum;
}
int main()
{
while(scanf("%d",&n),n)
{
memset(s,0,sizeof(s));
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i].v);
a[i].x=i;
}
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++)
{
t[a[i].x]=i;
}
long long ans=0;
for(int i=1;i<=n;i++)
{
modify(t[i],1);
ans+=i-query(t[i]);
}
printf("%lld\n",ans);
}
}