Reverse order refers to a series of a[1],a[2],a[3] ... Any two numbers in A[i],a[j] (i<j), if A[I]>A[J], then we say that these two numbers constitute an inverse pair.
While merging the sorted two permutations of the process
The elements of the ordered sequence on the right are inserted sequentially into the preceding sequential sequence.
E.G. (3 7 12) (5 6 8)
Insert 5 in (3 7 12)
Because the back is ordered, it assumes that all elements of 5 and left are in reverse order, so there are mid+1.
And the left sequence has start1 number than 5, so the reverse number is Mid+1-start1
This can greatly reduce the time to calculate the inverse number pairs.
#include <iostream> #include <cstdio> #include <cstring>using namespace Std;int a[500005],b[500005]; Long long ans;void merge (int left,int mid,int right) {int start1=left,start2=mid+1; int num=left; int i; while (start1<=mid&&start2<=right) {if (A[start1]>a[start2]) {Ans=ans+mid-sta rt1+1; B[num++]=a[start2++]; } else b[num++]=a[start1++]; } while (Start1<=mid) b[num++]=a[start1++]; while (Start2<=right) b[num++]=a[start2++]; for (i=left; i<=right; i++) a[i]=b[i]; return;} void mergesort (int left,int right) {int mid= (left+right)/2; if (left<right) {mergesort (left,mid); MergeSort (Mid+1,right); Merge (Left,mid,right); } return; int main () {int n; while (~SCANF ("%d", &n)) {ans=0; for (int i=1; i<=n; i++) scanf ("%d", &a[i]); MErgesort (1,n); printf ("%lld\n", ans); } return 0;}
Data structure Merge sort-inverse number pair