题意:给定一个整数序列 问 只允许相邻的两个数交换 至少需要交换多少次
思路:归并排序
#include<stdio.h> __int64 count; int array[500001],temp[500001]; void merge(int array[],int p,int q,int r) ///// p < = q < r { int begin1,end1,begin2,end2,k,i; begin1=p; end1=q; begin2=q+1; end2=r; k=0; while(begin1<=end1 && begin2<=end2) { if(array[begin1] < array[begin2]) { temp[k++]=array[begin1]; begin1++; count+=begin2-(q+1); } else { temp[k++]=array[begin2]; begin2++; } } while(begin1<=end1) { temp[k++]=array[begin1]; begin1++; count+=end2-q; } while(begin2<=end2) { temp[k++]=array[begin2]; begin2++; } for(i=p;i<=r;i++) array[i]=temp[i-p]; } void mergesort(int array[],int first,int last) { int mid=(first+last)/2; if(first<last) { mergesort(array,first,mid); mergesort(array,mid+1,last); merge(array,first,mid,last); } } int main() { int i,n; while(scanf("%d",&n)!=EOF) { if(n==0) break; for(i=1;i<=n;i++) scanf("%d",&array[i]); count=0; mergesort(array,1,n); printf("%I64d ",count); } return 0; }