标签:opera swap ace using namespace lines des 求逆 end
1、链接:
http://acm.hrbust.edu.cn/vj/index.php?c=problem-problem&id=216322
2、题目:
Description
You want to processe a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. Then how many times it need.
For example, 1 2 3 5 4, we only need one operation : swap 5 and 4.
Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 1000); the next line contains a permutation of the n integers from 1 to n.
Output
For each case, output the minimum times need to sort it in ascending order on a single line.
Sample Input
3
1 2 3
4
4 3 2 1
Sample Output
0
6
解题分析:
题意:求逆序数的个数
解法:归并排序的应用
代码:
#include<string.h> #include<stdio.h> #include<iostream> #include<algorithm> using namespace std; int sum; int temp[1005]; int a[1005]; void Merge(int a[],int l,int mid,int r){ int i=l,j=mid+1,k=0; while(i<=mid&&j<=r){ if(a[i]<a[j]){ temp[k++]=a[i++]; } else{ temp[k++]=a[j++]; sum+=mid-i+1; } } while(i<=mid) temp[k++]=a[i++]; while(j<=r) temp[k++]=a[j++]; for(int i=l,k=0;i<=r;k++,i++) a[i]=temp[k]; } void MergeSort(int a[],int l,int r){ int mid; if(l<r){ mid=(l+r)/2; MergeSort(a,l,mid); MergeSort(a,mid+1,r); Merge(a,l,mid,r); } } int main(){ int n; while(scanf("%d",&n)!=EOF){ sum=0; for(int i=0;i<n;i++) scanf("%d",&a[i]); MergeSort(a,0,n-1); printf("%d\n",sum); } return 0; }
标签:opera swap ace using namespace lines des 求逆 end
原文地址:http://www.cnblogs.com/hhkobeww/p/7831624.html