Suppose you have invented a sorting algorithm that sorts the given numbers in acending order. The method of your algorithm is pretty simple: select two adjacent numbers and swap their positions until the number sequence is sorted.
Now you want to examine your algorithm analytically. You want to find out the minimum number of swaps your algorithm will perform on a given sequence. Please write a program to do this job automatically.
For example, your algorithm may perform 5 swaps at least on sequence 5, 1, 2, 4, 3. Here's the process:
5,1,2,4,3 ---(swaps 5 with 1)---> 1,5,2,4,3 ---(swaps 5 with 2)---> 1,2,5,4,3 ---(swaps 5 with 4)---> 1,2,4,5,3 ---(swaps 5 with 3)---> 1,2,4,3,5 ---(swaps 4 with 3)---> 1,2,3,4,5 (DONE).
Input
The input file contains multiple test cases. Please process to the end of file.
The first line of each test cases contains a single integer , indicating the quantity of numbers in the original sequence to be sorted. The next line contains space-separated integers indicating the sequence itself. All numbers in the sequence is between and , inclusive. It is guaranteed that the sum of among all test cases in the input file will not exceed .
Output
For each test case, your program should generate a single line of output containing the minimum number of swaps your algorithm will perform on the given sequence.
测试输入 | 期待的输出 | 时间限制 | 内存限制 | 额外进程 | |
---|---|---|---|---|---|
测试用例 1 | 以文本方式显示
| 以文本方式显示
| 1秒 | 1024KB | 0 |
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
long long time=0;
void merge(int b[],int n1,int c[],int n2,int a[],int n)
{
int i=0,j=0,k=0,u;
while(i<n1&&j<n2)
{
if(b[i]<=c[j])
{
a[k]=b[i];
i++;
}
else
{
a[k]=c[j];
j++;
time+=(n1-i);
}
k++;
}
if(i==n1)
{
for(u=k;u<n;u++,j++) a[u]=c[j];
}
else
{
for(u=k;u<n;u++,i++) a[u]=b[i];
}
}
void insertsort(int a[],int n)
{
int temp,i,j;
for(i=1;i<n;i++)
{
temp=a[i];
for(j=i-1;j>=0;j--)
{
if(a[j]>temp)
{
a[j+1]=a[j];
time++;
}
else break;
}
a[j+1]=temp;
}
}
void mergesort(int a[],int n)
{
int i;
int n1,n2;
n1=floor((float)n/2);
n2=ceil((float)n/2);
if(n>1)
{
int b[n1],c[n2];
for(i=0;i<n1;i++) b[i]=a[i];
for(i=0;i<n2;i++) c[i]=a[i+n1];
if(n<500)
{
insertsort(b,n1);
insertsort(c,n2);
}
else
{
mergesort(b,n1);
mergesort(c,n2);
}
if(b[n1-1]<=c[0]) return;
else merge(b,n1,c,n2,a,n);
}
}
int main(){
int n,i;
int a[500010];
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<n;i++) scanf("%d",&a[i]);
mergesort(a,n);
printf("%ld\n",time);
time=0;
}
}