Topic 1348: Reverse order in an array for time limit: 1 seconds Memory limit: 32 Mega Special: No submission: 2133 Resolution: 500 title Description: Two numbers in the array, if the previous number is greater than the following number, then the two numbers form an inverse pair. Enter an array to find the total number of reverse pairs in this array. Input: Each test case consists of two lines: the first row contains an integer n, which represents the number of elements in the array. where 1 <= n <= 10^5. The second row contains n integers, and each array is of type int. Output: Corresponds to each test case, outputting an integer that represents the total number of reverse pairs in the array. Sample input: 47 5 6 4 Sample output: 5
#include <iostream> #include <stdio.h>using namespace std;typedef long Long ll;int N, arr[100010], tmp[100010 ];//merge sort, process statistics in reverse order number ll merge (int start, int mid, int end) {ll cnt = 0;int i = start, j = mid+1, K = Start;while (I<=mid &A mp;& j<= End) {//from large to small sort if (Arr[i] > Arr[j]) {cnt + = (end-j+1);////////The left of the right is reverse order tmp[k++] = arr[i++];} else{tmp[k++] = arr[j++];}} while (i<=mid) tmp[k++] = Arr[i++];while (j<=end) tmp[k++] = arr[j++];for (int i=start; i<=end; i++) arr[i] = Tmp[i] ; return CNT;} ll Inversepairs (int start, int end) {ll cnt = 0;if (Start < end) {int mid = (start + end)/2;cnt + = Inversepairs (Start, mid ); The left half is reversed to the number cnt + = Inversepairs (mid+1, end); Right half cnt + = merge (start, Mid, end); Combine two parts and calculate the quantity}return cnt;} int main () {while (scanf ("%d", &n)! = EOF) {for (int i=0; i<n; i++) scanf ("%d", &arr[i]); ll ans = inversepairs (0, n-1);p rintf ("%lld\n", ans);} return 0;}
Sword refers to the offer series source code-the reverse order in the array