Question: only the sorting of adjacent elements can be exchanged, and the minimum number of exchanges is counted.
Analysis: grouping, reverse order number. In the process of merging and sorting, the reverse order is solved.
When merging strings a and B, two pointers are used as the Count;
When elements in B are added to a new array, the remaining elements in a must be greater than B;
You can add each count.
Note: The replacement group can be used to calculate any minimum exchange... )
# Include <stdio. h> # include <stdlib. h> int data [500005]; int save [500005]; long mergesort (int A, int B) {if (a <B) {long l = mergesort (, (A + B)/2); long R = mergesort (A + B)/2 + 1, B); // merge Long Count = L + R; int PS = A, Pe = (a + B)/2; int Qs = (a + B)/2 + 1, Qe = B; int move =; while (Ps <= PE | QS <= QE) if (QS <= QE & (PS = PE + 1 | data [PS]> data [QS]) {save [move ++] = data [QS ++]; count + = pe-PS + 1ll; // calculate the number of reverse orders in a B} else save [move ++] = data [PS ++]; for (INT I = A; I <= B; ++ I) data [I] = save [I]; return count;} else return 0ll;} int main () {int N; while (scanf ("% d", & N) & N) {for (INT I = 1; I <= N; ++ I) scanf ("% d", & Data [I]); printf ("% LLD \ n", mergesort (1, N);} return 0 ;}
Zoj 2386-ultra-quicksort