逆序对的数量【AcWing】 本算法用归并排序的方法,间接求出序列中逆序对的数量。其思路为二路归并时,如果第二路序列中存在比第一路序列小的数,则此数为逆序的数,具体逆序数量为此时对应的第一路中的所有数的个数。第一路中元素个数的计算公式为 : temp = mid - i + 1; #include<stdio.h> #define N 100010 typedef long long LL; int n, nums[N]; LL reverseNum(int nums[], int l, int r) { if(l >= r) return 0; LL res; int mid = l + r >> 1; res = reverseNum(nums, l, mid) + reverseNum(nums, mid + 1, r); int i = l, j = mid + 1, k = 0, temp[r - l]; while(i <= mid && j <= r) { if(nums[i] <= nums[j]) temp[k++] = nums[i++]; else { temp[k++]= nums[j++]; res += mid - i + 1; } } while(i <= mid) temp[k++] = nums[i++]; while(j <= r) temp[k++] = nums[j++]; for(int i = 0, j = l; i < k; i++) nums[j++] = temp[i]; return res; } int main() { scanf("%d", &n); for(int i = 0; i < n; i++) scanf("%d", &nums[i]); int res = reverseNum(nums, 0, n - 1); printf("%lld", res); }