結果

問題 No.556 仁義なきサルたち
ユーザー takeya_okinotakeya_okino
提出日時 2019-07-20 12:46:04
言語 Java21
(openjdk 21)
結果
AC  
実行時間 429 ms / 2,000 ms
コード長 1,336 bytes
コンパイル時間 2,731 ms
コンパイル使用メモリ 74,104 KB
実行使用メモリ 62,660 KB
最終ジャッジ日時 2023-08-28 15:05:04
合計ジャッジ時間 8,426 ms
ジャッジサーバーID
(参考情報)
judge15 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 122 ms
55,808 KB
testcase_01 AC 129 ms
56,260 KB
testcase_02 AC 122 ms
56,248 KB
testcase_03 AC 123 ms
55,744 KB
testcase_04 AC 123 ms
55,680 KB
testcase_05 AC 151 ms
55,976 KB
testcase_06 AC 145 ms
56,376 KB
testcase_07 AC 152 ms
55,988 KB
testcase_08 AC 181 ms
55,900 KB
testcase_09 AC 209 ms
56,972 KB
testcase_10 AC 222 ms
56,676 KB
testcase_11 AC 234 ms
58,752 KB
testcase_12 AC 231 ms
58,928 KB
testcase_13 AC 245 ms
56,228 KB
testcase_14 AC 295 ms
61,252 KB
testcase_15 AC 312 ms
60,780 KB
testcase_16 AC 334 ms
60,688 KB
testcase_17 AC 363 ms
60,968 KB
testcase_18 AC 394 ms
60,680 KB
testcase_19 AC 413 ms
60,252 KB
testcase_20 AC 429 ms
60,884 KB
testcase_21 AC 405 ms
62,660 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
  static int[] par;
  static int[] rank;
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    par = new int[n + 1];
    rank = new int[n + 1];

    int M = sc.nextInt();
    init(n + 1);
    for(int i = 0; i < M; i++) {
      int a = sc.nextInt();
      int b = sc.nextInt();
      unite(a, b);
    }
    for(int i = 1; i < n + 1; i++) {
      System.out.println(find(i));
    }
  }
  static void init(int m) {
      for(int i = 0; i < m; i++) {
        par[i] = i;
        rank[i] = 1;
      }
    }
  static int find(int x) {
      if(par[x] == x) {
        return x;
      } else {
        return par[x] = find(par[x]);
      }
    }
  static void unite(int x, int y) {
      x = find(x);
      y = find(y);
      if(x != y) {
        if(rank[x] < rank[y]) {
          par[x] = y;
          rank[y] += rank[x];
        } else {
          if(rank[x] == rank[y]) {
            if(x > y) {
              par[x] = y;
              rank[y] += rank[x];
            } else {
              par[y] = x;
              rank[x] += rank[y];
            }
          } else {
            par[y] = x;
            rank[x] += rank[y];
          }
        }
      }
    }
  static boolean same(int x, int y) {
      return find(x) == find(y);
    }
}
0