The number of reverse order, that is, for n different elements, the first rule between the elements have a standard order (for example, n different natural numbers, can be specified from small to large for the standard order), so in any of the n elements of the arrangement, when a two elements of the sequence and the standard sequence is not the same, said there are 1 reverse. The total number of reverse order in a permutation is called the reverse number of this arrangement.
The number of times we move the elements into, if for each number da[i], the number of the previous than his large number of c[i], then the total number of moving elements should be c[0]+c[1]+......+c[n-1], is the number of reverse order of the sequence.
There are two ways of thinking about general solutions.
1, merge sort, merge row of words must be the best plan, subjectively think about each of the numbers are moving toward the target position (learning data structure of the word has a noun called stable sort, another stable sort is bubbling, the choice is obviously not).
2, use line tree tree array to do, for reverse order in another blog post is mentioned.
In terms of complexity, the first two sorts, Bubble O (n^2), merge O (Nlog (n)), and the tree array is O (Nlog (n)),
Code:
#include <iostream> #include <cstdio> #include <string> #include <cmath> #include <queue> #include <stack> #include <map> #include <cstring> #include <algorithm> #define REP (i,a,b) for ( int i= (a);i< (b) i++) #define REV (I,a,b) for (int i= (a); i>= (b); i--) #define CLR (a,x) memset (a,x,sizeof a) #define INF 0x3f3f3f3ftypedef Long long ll;using namespace std;const int mod=1e9 +7;const int maxn=2005;const int Maxm=4005;int A[MAXN ],tmp[maxn];int ans;void Merge (int l,int m,int r) {int i=l; int j=m+1; int k=l; while (i<=m&&j<=r) {if (A[i]>a[j]) {tmp[k++]=a[j++]; ans+=m-i+1; } else {tmp[k++]=a[i++]; }} while (I<=m) tmp[k++]=a[i++]; while (J<=R) tmp[k++]=a[j++]; for (int i=l;i<=r;i++) a[i]=tmp[i];} void Merge_sort (int l,int r) {if (l<r) {int m= (L+R) >>1; Merge_sort (L,M); Merge_sort (M+1,R); MeRge (L,M,R); }}int Main () {int t,n,cas=1; scanf ("%d", &t); while (t--) {scanf ("%d", &n); for (int i=0;i<n;i++) scanf ("%d", &a[i]); ans=0; Merge_sort (0,n-1); printf ("Scenario #%d:\n%d\n\n", Cas++,ans); } return 0;}
poj1804 (merge sort to find the reverse order number)