結果

問題 No.556 仁義なきサルたち
ユーザー neko_the_shadowneko_the_shadow
提出日時 2019-05-17 17:30:55
言語 Java19
(openjdk 21)
結果
AC  
実行時間 435 ms / 2,000 ms
コード長 1,764 bytes
コンパイル時間 2,262 ms
コンパイル使用メモリ 78,920 KB
実行使用メモリ 62,492 KB
最終ジャッジ日時 2023-10-17 07:22:56
合計ジャッジ時間 9,449 ms
ジャッジサーバーID
(参考情報)
judge11 / judge12
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 137 ms
57,488 KB
testcase_01 AC 142 ms
57,628 KB
testcase_02 AC 136 ms
57,444 KB
testcase_03 AC 137 ms
57,376 KB
testcase_04 AC 138 ms
57,564 KB
testcase_05 AC 156 ms
57,564 KB
testcase_06 AC 160 ms
57,480 KB
testcase_07 AC 169 ms
57,704 KB
testcase_08 AC 183 ms
57,856 KB
testcase_09 AC 212 ms
57,592 KB
testcase_10 AC 239 ms
58,172 KB
testcase_11 AC 230 ms
60,204 KB
testcase_12 AC 249 ms
60,656 KB
testcase_13 AC 270 ms
58,144 KB
testcase_14 AC 316 ms
62,372 KB
testcase_15 AC 326 ms
62,172 KB
testcase_16 AC 347 ms
62,492 KB
testcase_17 AC 373 ms
62,252 KB
testcase_18 AC 418 ms
62,252 KB
testcase_19 AC 407 ms
62,060 KB
testcase_20 AC 435 ms
62,056 KB
testcase_21 AC 430 ms
62,428 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        int n = stdin.nextInt();
        int m = stdin.nextInt();
        int[] a = new int[m];
        int[] b = new int[m];
        for (int i = 0; i < m; i++) {
            a[i] = stdin.nextInt() - 1;
            b[i] = stdin.nextInt() - 1;
        }
        
        UnionFind uf = new UnionFind(n);
        for (int i = 0; i < m; i++) {
            uf.union(a[i], b[i]);
        }
        
        for (int i = 0; i < n; i++) {
            System.out.println(uf.find(i) + 1);
        }
    }
    
    private static class UnionFind {
        private int[] parents;
        private int[] sizes;
        
        public UnionFind(int n) {
            parents = IntStream.range(0, n).toArray();
            sizes = new int[n];
            Arrays.fill(sizes, 1);
        }
        
        public int find(int x) {
            if (parents[x] == x) {
                return x;
            } else {
                parents[x] = find(parents[x]);
                return parents[x];
            }
        }
        
        public void union(int x, int y) {
            x = find(x);
            y = find(y);
            if (x == y) return ;
            
            
            int w, l;
            if (sizes[x] < sizes[y]) {
                w = y;
                l = x;
            } else if (sizes[x] == sizes[y]) {
                w = Math.min(x, y);
                l = Math.max(x, y);
            } else {
                w = x;
                l = y;
            }
            
            sizes[w] += sizes[l];
            parents[l] = w;
        }
    }
}
0