https://www.luogu.org/problem/show?pid=U4566
Obviously in reverse order, formerly just mouth AC, this time finally hit out.
Reverse order is actually a sort of bubble sort number .... But the general sort time complexity is O (n^2), so will think of merge sort ...
One or two-way merge
Two ordered arrays are known to be merged into an ordered array
Obviously, the first element is compared, the small throw into the destination array, and finally throw the rest in.
1 inta[n],b[m],tmp[n+m];2 intI=1, j=1, k=1;3 while(i<=n&&j<=m)4 {5 if(A[i]<a[j]) tmp[k++]=a[i++];6 Elsetmp[k++]=b[j++];7 }8 while(i<=n) tmp[k++]=a[i++];9 while(j<=m) tmp[k++]=a[j++];
Two-way merge
Second, merge sort
Using two-way merging to sort, can reach O (NLOGN);
The first is to divide the unordered array, so that the two parts with the midpoint as the boundary become orderly and then merge.
code see below.
Third, using merge sort to seek reverse order
In the merge sort, if the first element in the back part is less than the first element, then all the elements in the previous section are reversed ...
If less than will not have reverse order;
#include <iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>#include<cmath>#include<algorithm>#include<queue>#defineLL Long Long#defineFor1 (i,n,m) for (int i= (n); i<= (m); i++)#defineFor2 (i,n,m) for (int i= (n); i>= (m); i--)#defineMAXN 305000#defineMaxe 506000#defineINF 0x7fffffffusing namespacestd;intA[MAXN],TMP[MAXN]; LL ans;structedge{intx,v;}; Edge E[MAXN];voidMsort (intLintR//sorting the interval (l,r) Merge{ intmid; if(l>=R)return;//BorderMid= (l+r) >>1;//divide and conquer by midpointMsort (L,mid); Msort (Mid+1, R);//Merge and sort the two parts sequentially intI=l,j=mid+1, k=L; while(I<=MID&&J<=R)//Merge { if(a[i]>A[j]) {Tmp[k++]=a[j++]; Ans+=mid-i+1;//to find the inverse logarithm, note that here is minus I, not l; } Elsetmp[k++]=a[i++]; } while(I<=mid) tmp[k++]=a[i++]; while(j<=r) tmp[k++]=a[j++];//the remaining throw into the auxiliary arrayFor1 (t,l,r) a[t]=TMP[T];//change the original array }BOOLcmpConstEdge&q,Constedge&W) { returnq.x<w.x;}intMain () {Ios::sync_with_stdio (0); intN; CIN>>N; For1 (i,1, N) {cin>>e[i].x>>e[i].v; } sort (E+1, e+n+1, CMP); For1 (i,1, N) {A[i]=e[i].v; } msort (1, N); cout<<ans; return 0;}
Merge sort for reverse order
Merge sort for reverse order//(Rokua) U4566 race