結果

問題 No.556 仁義なきサルたち
ユーザー Kutimoti_T
提出日時 2018-06-28 21:29:41
言語 C++11(廃止可能性あり)
(gcc 13.3.0)
結果
WA  
実行時間 -
コード長 1,105 bytes
コンパイル時間 1,389 ms
コンパイル使用メモリ 163,976 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-06-30 23:33:00
合計ジャッジ時間 2,309 ms
ジャッジサーバーID
(参考情報)
judge3 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 12 WA * 10
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define rep(i,s,e) for(int (i) = (s);(i) <= (e);(i)++)

#include <vector>
using namespace std;

struct UnionFind {
  vector<int> par;
  vector<int> cnt;

  void init(int size) {
    par.resize(size, 0);
    cnt.resize(size,1);
    for (int i = 0; i < size; i++) {
      par[i] = i;
    }
  }
  int root(int x) { return par[x] == x ? x : par[x] = root(par[x]); }

  bool unite(int x, int y) {
    x = root(x);
    y = root(y);

    if(cnt[x] < cnt[y]){
      par[x] = y;
      cnt[y] += cnt[x];
      cnt[x] = 0;
    }
    else if(cnt[x] > cnt[y]){
      par[y] = x;
      cnt[x] += cnt[y];
      cnt[y] = 0;
    }
    else if(x > y){
      par[x] = y;
      cnt[y] += cnt[x];
      cnt[x] = 0;
    }
    else{
      par[y] = x;
      cnt[x] += cnt[y];
      cnt[y] = 0;
    }
    root(x);
    root(y);
    return true;
  }
};

int main(){
  int N;
  int M;
  cin >> N >> M;
  UnionFind uf;
  uf.init(N + 1);

  rep(i,0,M - 1){
    int a,b;
    cin >> a >> b;
    uf.unite(a,b);
  }

  rep(i,1,N){
    cout << uf.root(i) << endl;
  }
}

0