问题:
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 9 1 0 5 4 ,
Ultra-QuickSort produces the output 0 1 4 5 9 .
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence
element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.
Output
For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.
Sample Input
5
9
1
0
5
4
3
1
2
3
0
Sample Output
6
0
题意:给你n个数,让你排序从小到大,只有相邻的两个数才能调换,问你最少需要调换多少次?
归并排序:例给出8个数:5,4,7,9,3,8,2,1;
(1)流程:
(2)合并两个有序数组的流程
归并排序模板;
#include <iostream> using namespace std; void merge(int arr[],int l,int mid,int r) { int aux[r-l+1];//开辟一个新的数组,将原数组映射进去 for(int m=l; m<=r; m++) { aux[m-l]=arr[m]; } int i=l,j=mid+1;//i和j分别指向两个子数组开头部分 for(int k=l; k<=r; k++) { if(i>mid) { arr[k]=aux[j-l]; j++; } else if(j>r) { arr[k]=aux[i-l]; i++; } else if(aux[i-l]<aux[j-l]) { arr[k]=aux[i-l]; i++; } else { arr[k]=aux[j-l]; j++; } } } //递归的使用归并排序,对arr[l....r]排序 void merge_sort(int arr[],int l,int r) { if(l >=r) return ; int mid=(l+r)/2; merge_sort(arr,l,mid); merge_sort(arr,mid+1,r); merge(arr,l,mid,r); } void my_merge_sort(int arr[],int n) { merge_sort(arr,0,n-1); } int main() { int a[6]; for(int i=0; i<6; i++) cin>>a[i]; my_merge_sort(a,6); for(int i=0; i<6; i++) cout<<a[i]<<" "; return 0; }
本题答案代码:
#include<stdio.h> #include<string.h> #include<algorithm> #define N 510000 using namespace std; int a[N],aux[N]; long long ans; void paixu(int l,int r,int mid) { for(int i=l; i<=r; i++) aux[i-l]=a[i]; int L1=l,L2=mid+1; for(int i=l; i<=r; i++) { if(L1>mid) { a[i]=aux[L2-l]; L2++; } else if(L2>r) { a[i]=aux[L1-l]; L1++; } else if(aux[L1-l]>aux[L2-l]) { ans+=(mid-L1+1); a[i]=aux[L2-l]; L2++; } else { a[i]=aux[L1-l]; L1++; } } } void build(int l,int r) { if(l>=r) return ; int mid=(l+r)>>1; build(l,mid); build(mid+1,r); paixu(l,r,mid); } int main() { int n; while(~scanf("%d",&n)&&n) { ans=0; memset(a,0,sizeof(a)); for(int i=0; i<n; i++) scanf("%d",&a[i]); build(0,n-1); printf("%lld\n",ans); } }