标签:
| Time Limit: 7000MS | Memory Limit: 65536K | |
| Total Submissions: 48121 | Accepted: 17553 |
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 Input
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
Source
#include<cstdio>
#include<cstring>
#include<algorithm>
int A[500004],T[500004];
long long cnt;
using namespace std;
void init(int n)
{
for(int i=0;i<n;i++)
scanf("%d",&A[i]);
}
void merge_sort(int *A,int x,int y,int *T)
{
if(y-x>1)
{
int m=x+(y-x)/2;
int p=x,q=m,i=x;
merge_sort(A,x,m,T);
merge_sort(A,m,y,T);
while(p<m||q<y)
{
if(q>=y||(p<m&&A[p]<=A[q])) T[i++]=A[p++];
else
{
T[i++]=A[q++];
cnt+=m-p;
}
} for(i=x;i<y;i++)
A[i]=T[i];
}
}
int main()
{
int n;
while(scanf("%d",&n)&&n)
{
init(n);
cnt=0;
memset(T,0,sizeof(T));
merge_sort(A,0,n,T);//不能把n写成n-1,否则会答案错误
printf("%I64d\n",cnt);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/a1967919189/article/details/47257677