a877中等

Swaps in Permutation

把同一可交換區塊的最大值移到最前位置。

解題思路

把位置當作頂點、允許交換當作無向邊,以並查集合併。沿一條路徑來回交換可交換兩端,因此每個連通分量內可實現任意排列;不同分量的值不能互換。

依位置從小到大收集各分量,再將其數值由大到小填回。若最前方尚未決定的位置沒有放該分量剩餘最大值,換入最大值會令字典序嚴格增加,故逐位貪心正確。

時間 O((n+m)α(n)+n log n),空間 O(n);輸入也需讀取 m 條邊。

Step-by-step animation

教學示意(以步驟描述中的輸入為準)

回報動畫錯誤
步驟 1 / 3

建立分量

示意排列為 1 2 3 4,允許交換 1 與 3。

1
2
3
4
分量
{1,3},{2},{4}

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m;
    cin >> n >> m;
    vector<int> p(n), f(n), sz(n, 1);
    iota(f.begin(), f.end(), 0);
    for (int &x : p)
        cin >> x;
    auto find = [&](int x) {
        while (x != f[x])
            x = f[x] = f[f[x]];
        return x;
    };
    while (m--) {
        int a, b;
        cin >> a >> b;
        a = find(a - 1);
        b = find(b - 1);
        if (a != b) {
            if (sz[a] < sz[b])
                swap(a, b);
            f[b] = a;
            sz[a] += sz[b];
        }
    }
    vector<vector<int>> g(n);
    for (int i = 0; i < n; i++)
        g[find(i)].push_back(i);
    for (auto &v : g) {
        vector<int> w;
        for (int i : v)
            w.push_back(p[i]);
        sort(w.rbegin(), w.rend());
        for (int j = 0; j < (int)v.size(); j++)
            p[v[j]] = w[j];
    }
    for (int i = 0; i < n; i++)
        cout << p[i] << (i + 1 == n ? '\n' : ' ');
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多