Title Link: http://acm.hdu.edu.cn/showproblem.php?pid=1394
Understand the merger sort, learn a bit of other people's blog, have the topic to knock over ...
This problem I use merge sort is I currently the fastest algorithm 62ms ... Of course, in my blog There are also wired and tree arrays to find the reverse number of the template;
Here I do not discretization, but not all the reverse number of templates ...
I recommend a blog with a very detailed illustration of what I don't know about merge sort; Link: http://www.cnblogs.com/jillzhang/archive/2007/09/16/894936.html
#include <iostream> #include <string> #include <cstdio> #include <cstring> #include <queue > #include <map> #include <cmath> #include <stack> #include <set> #include <vector># Include<algorithm> #define LL Long long#define inf 1<<30#define s (a) scanf ("%d", &a) #define Clear (A, B) memset (A,b,sizeof (a)) using namespace Std;const int n=200005;int n,ans;int a[n],b[n];void merge_array (int l,int mid,int R )//two-way merge; {int i=l,j=mid+1,k=0; int *p; p= (int *) malloc ((r-l+1) *sizeof (int)); while (i<=mid&&j<=r) {if (A[i]<=a[j]) {p[k++]=a[i++]; }else{p[k++]=a[j++]; ans+=mid-i+1; }} while (I<=mid) {p[k++]=a[i++]; } while (J<=r) {p[k++]=a[j++]; } int cnt=0; for (int i=l;i<=r;i++) {a[i]=p[cnt++]; } free (p);} void Merge_sort (int l,int R)//divide-and-conquer method, call recursion; {if (l<r) {int mid= (L+R) >>1; Merge_sort (l, mid); Merge_sort (MID+1,R); Merge_array (L,MID,R); }}int Main () {while (~SCANF ("%d", &n) {ans=0; for (int i=0;i<n;i++) {s (a[i]); b[i]=a[i];} Merge_sort (0,n-1); Sort from 0 to n-1; int Cnt=ans; for (int i=0;i<n;i++) {ans=ans-b[i]+n-1-b[i]; if (Cnt>ans) Cnt=ans; } printf ("%d\n", CNT); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hdu1394-minimum inversion number-Merge sort to find the minimum number of reverse order