結果

問題 No.101 ぐるぐる!あみだくじ!
ユーザー srjywrdnprkt
提出日時 2022-12-21 09:02:02
言語 C++17(clang)
(17.0.6 + boost 1.87.0)
結果
AC  
実行時間 3 ms / 5,000 ms
コード長 1,486 bytes
コンパイル時間 4,212 ms
コンパイル使用メモリ 145,000 KB
実行使用メモリ 6,820 KB
最終ジャッジ日時 2024-11-18 02:35:43
合計ジャッジ時間 2,468 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <vector>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <queue>
#include <algorithm>
#include <numeric>
#include <deque>

using namespace std;
 
struct UnionFind {
    vector<long long> par;
    vector<long long> siz;

    UnionFind(long long N) : par(N), siz(N) {
        for(long long i = 0; i < N; i++){
            par[i] = i;
            siz[i] = 1;
        }   
    }   
 
    long long root(long long x) {
        if (par[x] == x) return x;
        return par[x] = root(par[x]);
    }   
 
    long long unite(long long x, long long y) {
        long long rx = root(x);
        long long ry = root(y);
        if (rx == ry) return rx; 
        if (siz[rx] > siz[ry]) swap(rx, ry);
        par[rx] = ry; 
        siz[ry] += siz[rx];
        return ry; 
    }   
 
    bool same(long long x, long long y) {
        long long rx = root(x);
        long long ry = root(y);
        return rx == ry; 
    }   
 
    long long size(long long x){ 
        return siz[root(x)];
    }   
};

int main(){
 
    long long N, M, ans=1, x, y;
    cin >> N >> M;
    vector<long long> A(N+1);
    UnionFind tree(N+1);
    for (int i=1; i<=N; i++) A[i] = i;
 
    for (int i=0; i<M; i++){
        cin >> x >> y;
        swap(A[x], A[y]);
    }
 
    for (int i=1; i<=N; i++) tree.unite(i, A[i]);

    for (int i=1; i<=N; i++){
        if (tree.root(i) == i) ans = lcm(ans, tree.size(i));
    }

    cout << ans << endl;
 
    return 0;
}
0