1311:【例2.5】求逆序对

#include <bits/stdc++.h>
using namespace std;


const int N = 1e5 + 9;
int a[N], b[N];
long long n, ans = 0;


void msort(int l, int r) {
    if (l == r) {
        return ;
    }
    int mid = (l + r) / 2;
    msort(l, mid);
    msort(mid + 1, r);
    int i = l, j = mid + 1, k = l;
    while (i <= mid && j <= r) {
        if (a[i] <= a[j]) {
            b[k] = a[i];

            i++;
        } else {
            b[k] = a[j];

            j++;
            ans += mid - i + 1;
        }
        k++;
    }
    while (i <= mid)
        b[k++] = a[i++];
    while (j <= r)
        b[k++] = a[j++];


    for (int i = l; i <= r; i++) {
        a[i] = b[i];
    }

}

int main() {


    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }

    msort(0, n - 1);

    cout << ans;

    return 0;
}

### 关于逆序对算法实现与解题思路 #### 归并排序方法用于计算逆序对数量 对于给定的一个序列 \( a_1, a_2, \ldots, a_n \),当存在索引 i 和 j 满足条件 \( i < j \) 并且 \( a_i > a_j \) 时,则称为一对逆序对。为了高效地统计这些逆序对的数量,可以采用基于分治策略的归并排序来解决问题[^2]。 在标准归并排序的过程中,每当右侧子数组中的某个元素被合并到最终有序数组之前,意味着左侧剩余未处理的所有元素都构成了新的逆序对(因为此时左边所有的数均大于右边当前要加入的那个较小数值)。因此,在每次执行合并操作的同时累加相应的计数器即可得到总的逆序对数目。 下面是具体的 Python 实现: ```python def merge_and_count_split_inv(B, C): sorted_array = [] inversions = 0 i, j = 0, 0 while i < len(B) and j < len(C): if B[i] <= C[j]: sorted_array.append(B[i]) i += 1 else: sorted_array.append(C[j]) inversions += len(B) - i # Count split inversions here. j += 1 # Append any remaining elements from either list to the end of `sorted_array`. sorted_array.extend(B[i:]) sorted_array.extend(C[j:]) return sorted_array, inversions def sort_and_count(A): n = len(A) if n == 1: return A, 0 else: mid = n // 2 B, X = sort_and_count(A[:mid]) # Recursively count left half C, Y = sort_and_count(A[mid:]) # Recursively count right half D, Z = merge_and_count_split_inv(B, C) return D, X + Y + Z # Return combined result with total inversion counts. # Example usage: arr = [int(x) for x in "1 3 5 2 4 6".split()] _, num_inversions = sort_and_count(arr) print(f"The number of inversions is {num_inversions}.") ``` 此代码片段展示了如何利用改进版的归并排序函数`sort_and_count()` 来有效地找出所有可能存在的逆序对,并返回它们的具体数量。这种方法的时间复杂度为 O(n log n),适用于较大规模的数据集而不至于因性能瓶颈而超时。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值