Tag: merge sort to find the logarithm of inverse number
title Link: http://codeforces.com/gym/100609/attachmentsThe main topic: There are n cards, each card has red and blue on both sides, the two sides have written some numbers, the same color of any two numbers in the front of the number than the number of rows in the back is called a pair of reverse. How to order the lowest number of reverse orders. problem-solving ideas: one of the colors of the number is the order and this color number corresponds to the other color of the number is the order of the number of reverse sequence to get the least logarithm. The difficulty lies in finding the logarithm of inverse number. Because of the large number O (n^2) complexity can not be satisfied, here according to the principle of merging sorted by how many of each number is larger than its number, and finally add up is the answer. Merge sort complexity is O (n). The code is as follows:
#include <cstdio> #include <algorithm> #include <cstring> #define LL long longusing namespace std; const int MAXN=100005;LL ans;int data[maxn];int n;struct node{int a b;} S[MAXN];LL CMP (node P,node q) {if (P.A==Q.A) return p.b<q.b; else return p.a<q.a;} void merge (int l,int mid,int R)//merge {int k=0,i=l,j=mid+1; int TAR[MAXN]; A temporary array is used to temporarily store ordered sequences while (I<=MID&&J<=R)//combine two sets of ordered series A[l]...a[mid] and A[mid+1]...a[r] into a set of ordered sequences tar[0]...tar[ R-l+1] {if (data[i]<=data[j])//Put a small number to the array tar[] tar[k++]=data[i++]; else {tar[k++]=data[j++]; ans+=mid-i+1; The key point, which has the smallest number in the latter group, indicates that the number remaining in the previous set is greater than the number, and that each number in the previous set of numbers is in the front of the next set of columns} while (I<=mid) tar[k++]=data[i++] ; while (J<=R) tar[k++]=data[j++]; for (k=0,i=l;i<=r;)//Copy ordered series to Data[l]. Data[r],data[] values are changed, become ordered, and ensure that the conditions are satisfied when merging an ordered sequence of data[i++]=tar[k++];} void MergeSort (int l, int R)//Sort {if (l<r) {int mid= (L+R)/2; MergeSort (L,mid); MergeSort (MID+1,R); Merge (L,MID,R); }}int Main (void) {while (scanf ("%d", &n)!=eof) {memset (data,0,sizeof (data)); for (int i=0;i<n;i++) scanf ("%d%d", &s[i].a,&s[i].b); Sort (s,s+n,cmp); for (int i=0;i<n;i++) data[i]=s[i].b; ans=0; MergeSort (0,n-1); printf ("%i64d\n", ans); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
ACM ICPC 2011–2012, NEERC, Northern subregional Contest J. John's inversions (combined sort to find the logarithm of reverse order)