Original article Portal
Well, the last time we said this problem can be done in a merge order.
But I will not merge the sort of pot (really konjac konjac. )
Get up in the morning and learn.
It seems to be quite simple.
233~
All right, cut to the chase.
Merging sort is actually using the thought of divide and conquer.
Divide and conquer: Divide a big problem into 2 small problems, then solve all the small problems, then merge the answers.
For example, let's take a sequence and merge it into a sort.
a[10]={9,2,3,5,4,6,6,7,9,5}
The order of merging is like this
{9,2,3,5,4} {6,6,7,9,5};
{9,2,3} {5,4} {6,6,7} {9,5};
{9,2} {3} {5,4} {6,6} {7} {9,5}
After this step, there are 2 ways to do this:
The first is to continue to divide, then merge, the second is not divided, and then determine the size of the 2 number of relationships, such as {9 2} into {2 9} and then merge. (In fact, the complexity of the same, is a few constants.) )
Merge process: (next to the table)
{2,9} {3} {4 5} {6 6} {7} {5 9}
{2,3,9} {4,5} {6,6,7} {5,9}
{2,3,4,5,9} {5,6,6,7,9}
{2,3,4,5,5,6,6,7,9,9}
Well, that's it.
The combined code implementation is to put 2 arrays of 2 pointers.
Scan, compare.
And put the results back in the original array.
Well, it's not very clear what I'm saying.
Let's just go to the code.
#include <iostream>#include<cstdio>#include<algorithm>#defineMoD 99999997using namespacestd;structlisan{intOpt,value;} a[100001],b[100001];intresult[100001],c[100001],d[100001],ans,n;BOOLCMP (Lisan A,lisan b) {returna.value<B.value;}voidMergeSort (intLeftintRight ) { if(Left>=right)return ; intMid= (left+right) >>1, I,j,k; MergeSort (Left,mid); MergeSort (Mid+1, right); for(i=left,j=mid+1, k=left;i<=mid&&j<=right;k++) { if(C[i]<c[j]) d[k]=c[i++]; Elseans+=mid-i+1, ans%=mod,d[k]=c[j++]; } while(i<=mid) D[k++]=c[i++]; while(j<=Right ) D[k++]=c[j++]; for(i=left;i<=right;i++) C[i]=d[i];}intMain () {scanf ("%d",&N); for(intI=1; i<=n;i++) {scanf ("%d",&a[i].value); A[i].opt=i; } for(intI=1; i<=n;i++) {scanf ("%d",&b[i].value); B[i].opt=i; } sort (A+1, a+n+1, CMP); Sort (b+1, b+n+1, CMP); for(intI=1; i<=n;i++) c[b[i].opt]=a[i].opt; MergeSort (1, N); printf ("%d", ans);}
Faster than a tree-like array. (Tree-shaped array back pot: )
Actually all O (Nlogn) is just a little constant.
Well, that's it.
Line-segment tree algorithm and chaotic algorithm still go to die. (Wait for me to become the Konjac Konjac in the big God to come back to mend. )
or a match line (fill in the pot of the merge sort)