Codeforces Global Round 9 E. Inversion SwapSort

题目链接:https://codeforces.com/contest/1375/problem/E

题意

给出一个大小为 $n$ 的数组 $a$,对数组中的所有逆序对进行排序,要求按照排序后的顺序交换每一对逆序对后数组为非递减数组。

题解

先将顺组的下标按元素大小排为非递减序,此即交换完所有的逆序对后得到的下标序列。

再对下标序列进行冒泡排序还原到初始时的 $0, 1, 2, dots, n - 1$,冒泡排序中的交换顺序即为逆序对的排列顺序。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n; cin >> n;
    int a[n] = {};
    for (int i = 0; i < n; i++)
        cin >> a[i];
    int p[n] = {};
    iota(p, p + n, 0);
    sort(p, p + n, [&] (int x, int y) {
        if (a[x] != a[y]) return a[x] < a[y];
        else return x < y;
    });
    vector<pair<int, int>> res;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j + 1 < n; j++) {
            if (p[j] > p[j + 1]) {
                res.emplace_back(p[j + 1], p[j]);
                swap(p[j], p[j + 1]);
            }
        }
    }
    cout << res.size() << "
";
    for (auto i : res)
        cout << i.first + 1 << ' ' << i.second + 1 << "
";
}
原文地址:https://www.cnblogs.com/Kanoon/p/13264219.html