1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public long cnt = 0; public long mod = 1000000007;
public void Merge(int[] array, int[] temp, int l, int r) { if(l>=r) return; int mid=(l+r)/2; int pos=l,lpos=l,rpos=mid+1; while (lpos<=mid&&rpos<=r) { if (array[lpos]<=array[rpos]){ temp[pos]=array[lpos]; lpos++; }else { temp[pos]=array[rpos]; cnt+=rpos-pos; cnt=(cnt+mod)%mod; rpos++; } pos++; } while(lpos<=mid){ temp[pos]=array[lpos]; lpos++; pos++; } while(rpos<=r){ temp[pos]=array[rpos]; rpos++; pos++; } for (int i = l; i <= r; i++) { array[i]=temp[i]; } }
public void MergeSort(int[] array, int[] temp, int l, int r) { int cnt; if (l >= r) return; int mid = (l + r) / 2; MergeSort(array, temp, l, mid); MergeSort(array, temp, mid + 1, r); Merge(array,temp, l, r); }
public int InversePairs(int[] array) { cnt = 0; int[] temp = new int[array.length]; MergeSort(array, temp, 0, array.length - 1); return (int) cnt; }
|