编辑代码

#include <iostream>
#include <vector>
 
const int MOD = 1000000007;
 
// 归并函数:将两个有序数组合并为一个有序数组,并统计逆序对的数量
int merge(std::vector<int>& nums, int start, int mid, int end) {
    std::vector<int> temp(end - start + 1);  // 临时数组用于存储合并后的有序序列
    int count = 0;  // 统计逆序对的数量
    int i = start;  // 左序列指针
    int j = mid + 1;  // 右序列指针
    int k = 0;  // 临时数组指针
 
    while (i <= mid && j <= end) {
        if (nums[i] <= nums[j]) {
            temp[k++] = nums[i++];
        } else {
            temp[k++] = nums[j++];
            count = (count + mid - i + 1) % MOD;  // 统计逆序对数量
        }
    }
 
    while (i <= mid) {
        temp[k++] = nums[i++];
    }
 
    while (j <= end) {
        temp[k++] = nums[j++];
    }
 
    for (i = start, k = 0; i <= end; i++, k++) {
        nums[i] = temp[k];  // 将合并后的有序序列复制回原数组
    }
 
    return count;
}
 
// 归并排序函数:递归地对数组进行归并排序,并返回逆序对的数量
int mergeSort(std::vector<int>& nums, int start, int end) {
    if (start >= end) {
        return 0;
    }
 
    int mid = start + (end - start) / 2;
 
    int count = 0;
    count = (count + mergeSort(nums, start, mid)) % MOD;  // 统计左半部分逆序对数量
    count = (count + mergeSort(nums, mid + 1, end)) % MOD;  // 统计右半部分逆序对数量
    count = (count + merge(nums, start, mid, end)) % MOD;  // 合并两部分并统计逆序对数量
 
    return count;
}
 
// 统计逆序对的总数并取模
int countInversePairs(std::vector<int>& nums) {
    int count = mergeSort(nums, 0, nums.size() - 1);
    return count;
}
 
int main() {
    std::vector<int> nums = {7, 5, 6, 4};
    int count = countInversePairs(nums);
    std::cout << "逆序对的数量为: " << count << std::endl;
 
    return 0;
}