"Title description"
Now given a permutation of,..., N, the number of reverse order is obtained.
"Input Format"
The first line is an integer n, which indicates that the permutation has n numbers (n <= 100000).
The second line is n different positive integers, separated by a space, indicating the arrangement.
"Output Format"
Outputs the number of reverse order for this arrangement.
Analysis
(1) the interval [1..N] is divided, the interval [1,mid] and [mid+1,n] are calculated first, and the sub-interval is divided by two until there is only one element in the interval.
(2) Merging the sub-ranges that have already been ordered, that is, using ordered [L,k][k+1,r] to find an ordered interval [l,r] to eventually merge into an interval [1,n], and the merging interval is divided into several steps:
① make i=j,j=mid+1, variable k=l, perform the next step.
② if I<=mid, and J<=r, if A[I]<A[J], then c[sum]=a[i],i++,sum++;
If A[I]>=A[J], then c[sum]=a[j],j++,sum++, perform the next step, if i>k, or j>r, then put the remaining elements of an interval into the C array, perform the next step.
③ if Sum>r, jump out of the loop.
For reverse order: In the second step of the merging interval in a[i]<a[j] ans+=mid-i+1 can be, the a[j] than the interval [i,mid] any one of the elements are small, and position in front of J, provides mid-i+1 reverse order.
Code
1#include <bits/stdc++.h>2 3 using namespacestd;4 5typedefLong LongLL;6 7 inta[100010],c[100010];8 intN;9LL ans=0;Ten One voidMerge_sort (intLintR) { A intMid= (l+r) >>1, i=l,j=mid+1, K; - if(L>=R)return; - Merge_sort (l,mid); theMerge_sort (mid+1, R); -k=l; - while(i<=mid&&j<=R) { - if(a[i]>A[j]) { +c[k++]=a[j++]; -ans+=mid-i+1; + } A Elsec[k++]=a[i++]; at } - while(I<=mid) c[k++]=a[i++]; - while(j<=r) c[k++]=a[j++]; - for(i=l;i<=r;i++) a[i]=C[i]; - } - in intMain () - { toscanf"%d",&n); + for(intI=1; i<=n;i++) scanf ("%d",&a[i]); -Merge_sort (1, n); theprintf"%lld\n", ans); * return 0; $}
Merge sort for reverse order