#include "stdio.h"
const int maxn = 100005;
int a[maxn],b[maxn];
int n;
__int64 ans;
void MergeArray( int ld,int mid ,int ed )
{
int i = ld, j = mid + 1;
int k = ld;
while( i <= mid && j <= ed )
{
if( a[i] <= a[j] )
{
b[k] = a[i];
ans += a[i]*( k - i );
i++;k++;
}
else
{
b[k] = a[j];
ans += a[j]*( j - k );
j++;k++;
}
}
while( i <= mid )
{
b[k] = a[i];
ans += a[i]*( k - i );
i++;k++;
}
while( j <= ed )
{
b[k] = a[j];
ans += a[j]*( j - k );
j++;k++;
}
for( i=ld;i<k;i++ )
a[i] = b[i];
}
void MergeSort( int ld, int ed )
{
if( ld < ed )
{
int mid = ( ld + ed )/2;
MergeSort( ld,mid );
MergeSort( mid+1,ed );
MergeArray( ld,mid,ed );
}
}
int main()
{
int i;
while( scanf("%d",&n)!=EOF )
{
for( i=1;i<=n;i++ )
{
scanf("%d",&a[i]);
}
ans = 0;
MergeSort( 1,n );
printf("%I64d\n",ans);
}
return 0;
}
fafu 1097 归并排序
最新推荐文章于 2021-05-23 04:11:02 发布