Links: Poj 2299
Test Instructions : gives a sequence of length n, which can only exchange two adjacent elements at a time.
Ask at least a few times to make the sequence an ascending sequence
Analysis : Bubble sort can only swap adjacent two elements at a time. That is to ask
use bubble sort to make it the number of interchanges of an ascending sequence, every time I exchange a record.
However, this data is larger, the bubble sort efficiency is low, will time out
In this case, we can use the merge sort to find the inverse number of the sequence by using the merge sort .
and the number of reverse order of a sequence = Only allow two adjacent elements to exchange, to get an ordered sequence of the number of exchanges
#include <stdio.h> #include <stdlib.h> #define M 500000int a[m+5],l[m+5],r[m+5];__int64 t;void cmp (int ll, int Mid,int rr) { int m=0,n=0,i,j,k; for (i=ll;i<=mid;i++) l[m++]=a[i]; for (i=mid+1;i<=rr;i++) r[n++]=a[i]; i=j=0; K=ll; while (i<m&&j<n) { if (L[i]<=r[j]) a[k++]=l[i++]; else{ a[k++]=r[j++]; T+=m-i; Calculates the number of reverse order } } while (i<m) a[k++]=l[i++]; while (j<n) a[k++]=r[j++];} void MergeSort (int l,int r) { int mid; if (l<r) { mid= (l+r)/2; MergeSort (l,mid); MergeSort (mid+1,r); CMP (L,MID,R);} } int main () { int n,i; while (scanf ("%d", &n) &&n) { for (i=0;i<n;i++) scanf ("%d", &a[i]); t=0; MergeSort (0,n-1); printf ("%i64d\n", t); } return 0;}
Poj 2299 ultra-quicksort (merge sort, reverse number)