Reverse Order pairs in the array
Two numbers in the array. If the first number is greater than the subsequent number, the two numbers form a reverse order. Enter an array to find the total number of reverse pairs in this array.
Input:
Each test case contains two rows: the first row contains an integer N, indicating the number of elements in the array. 1 <= n <= 10 ^ 5. The second row contains N integers, each of which is of the int type.
Output:
For each test case, an integer is output, indicating the total number of Reverse Order pairs in the array.
Sample input:
47 5 6 4
Sample output:
5
Ideas
The idea of grouping, counting the reverse order pairs inside the two sides, and the reverse order pairs between the left and right sides
Code
Long long merge2part (vector <int> & Nums, int start, int mid, int end) {vector <int> TMP; int P = start; int q = Mid + 1; long long npair = 0; while (P <= Mid & q <= END) {If (Nums [p] <= Nums [Q]) {TMP. push_back (Nums [p ++]);} else {TMP. push_back (Nums [q ++]); npair + = mid-p + 1; // core} while (P <= mid) {TMP. push_back (Nums [p ++]);} while (q <= END) {TMP. push_back (Nums [q ++]);}/* For (int n: TMP) {Nums [I ++] = N ;}*/INT I = start; For (vector <int >:: iterator it = TMP. Begin (); it! = TMP. end (); ++ it) {Nums [I ++] = * it;} return npair;} long reversepair (vector <int> & Nums, int start, int end) {If (Start> = END) return 0; int mid = (start + end)/2; long npair = 0; // depending on the data volume provided, estimated npair will exceed the int range npair + = reversepair (Nums, start, mid); // The mid should be in the first half segment (23 | 45) npair + = reversepair (Nums, mid + 1, end); npair + = merge2part (Nums, start, mid, end); Return npair;} int main () {int A, B; vector <int> Nums; while (CIN> A) {nums. clear (); // do not forget to clear while (A --> 0 & CIN> B) {nums. push_back (B);} cout <reversepair (Nums, 0, Nums. size ()-1) <Endl;} return 0 ;} /*************************************** * *********************** problem: 1348 language: C ++ result: accepted time: 240 MS memory: 3064 kb ************************************** **************************/