結果

問題 No.2289 順列ソート
ユーザー intfansintfans
提出日時 2023-05-05 21:41:59
言語 C++17(clang)
(17.0.6 + boost 1.83.0)
結果
AC  
実行時間 2 ms / 2,000 ms
コード長 1,358 bytes
コンパイル時間 4,632 ms
コンパイル使用メモリ 135,424 KB
実行使用メモリ 4,384 KB
最終ジャッジ日時 2023-08-15 03:25:50
合計ジャッジ時間 6,650 ms
ジャッジサーバーID
(参考情報)
judge14 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 2 ms
4,380 KB
testcase_01 AC 2 ms
4,384 KB
testcase_02 AC 2 ms
4,380 KB
testcase_03 AC 2 ms
4,380 KB
testcase_04 AC 2 ms
4,380 KB
testcase_05 AC 2 ms
4,380 KB
testcase_06 AC 1 ms
4,384 KB
testcase_07 AC 2 ms
4,384 KB
testcase_08 AC 2 ms
4,380 KB
testcase_09 AC 1 ms
4,384 KB
testcase_10 AC 2 ms
4,380 KB
testcase_11 AC 2 ms
4,384 KB
testcase_12 AC 2 ms
4,380 KB
testcase_13 AC 2 ms
4,384 KB
testcase_14 AC 2 ms
4,384 KB
testcase_15 AC 2 ms
4,384 KB
testcase_16 AC 2 ms
4,380 KB
testcase_17 AC 2 ms
4,384 KB
testcase_18 AC 2 ms
4,384 KB
testcase_19 AC 1 ms
4,380 KB
testcase_20 AC 1 ms
4,380 KB
testcase_21 AC 2 ms
4,384 KB
testcase_22 AC 1 ms
4,380 KB
testcase_23 AC 2 ms
4,384 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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

using ll = long long;

struct DSU {
    vector<int> p, siz;
    DSU(int n) : p(n), siz(n, 1) { iota(p.begin(), p.end(), 0); }
    inline int get(int x) { return (x == p[x] ? x : (p[x] = get(p[x])));}
    bool same(int x, int y) { return get(x) == get(y); }
    bool merge(int x, int y) {
        x = get(x), y = get(y);
        if (x == y) return false;
        siz[x] += siz[y];
        p[y] = x;
        return true;
    }
    int size(int x) { return siz[get(x)]; }
    vector<vector<int>> groups() {
        vector<vector<int>> res(p.size());
        for (int i = 0; i < p.size(); i++) res[get(i)].push_back(i);
        res.erase(
            remove_if(res.begin(), res.end(),
                           [&](const vector<int>& v) { return v.empty(); }),
            res.end());
        return res;
    }
};


int main() {
    ios::sync_with_stdio(false); cin.tie(nullptr);
    
    int n;
    cin >> n;
    vector<int> a(n), vis(n);
    for (int i = 0; i < n; ++i) {
    	cin >> a[i];
    	a[i]--;
    }

    DSU d(n);

    int ans = 0;

    for (int i = 0; i < n; ++i) {
    	int x = i;
    	while (!vis[x]) {
    		d.merge(x, a[x]);
    		vis[x] = 1;
    		x = a[x];
    	}
    }

    auto p = d.groups();

    for (auto &v : p) {
    	ans += v.size() - 1;
    }

    cout << ans << '\n';
    return 0;
}
0