結果

問題 No.556 仁義なきサルたち
ユーザー htensaihtensai
提出日時 2019-11-14 23:22:32
言語 Java21
(openjdk 21)
結果
AC  
実行時間 322 ms / 2,000 ms
コード長 1,402 bytes
コンパイル時間 1,925 ms
コンパイル使用メモリ 77,312 KB
実行使用メモリ 61,896 KB
最終ジャッジ日時 2023-10-22 03:47:27
合計ジャッジ時間 7,334 ms
ジャッジサーバーID
(参考情報)
judge12 / judge9
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 120 ms
57,220 KB
testcase_01 AC 130 ms
57,636 KB
testcase_02 AC 118 ms
57,576 KB
testcase_03 AC 118 ms
57,516 KB
testcase_04 AC 131 ms
57,436 KB
testcase_05 AC 136 ms
57,640 KB
testcase_06 AC 136 ms
57,316 KB
testcase_07 AC 151 ms
57,348 KB
testcase_08 AC 180 ms
57,672 KB
testcase_09 AC 147 ms
57,376 KB
testcase_10 AC 173 ms
55,792 KB
testcase_11 AC 179 ms
59,952 KB
testcase_12 AC 187 ms
59,932 KB
testcase_13 AC 176 ms
57,708 KB
testcase_14 AC 213 ms
60,884 KB
testcase_15 AC 225 ms
60,944 KB
testcase_16 AC 226 ms
60,684 KB
testcase_17 AC 251 ms
61,412 KB
testcase_18 AC 284 ms
61,896 KB
testcase_19 AC 297 ms
61,796 KB
testcase_20 AC 322 ms
61,704 KB
testcase_21 AC 282 ms
60,864 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.*;

public class Main {
	public static void main (String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		UnionFindTree uft = new UnionFindTree(n);
		for (int i = 0; i < m; i++) {
		    int a = sc.nextInt() - 1;
		    int b = sc.nextInt() - 1;
		    uft.unite(a, b);
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < n; i++) {
		    sb.append(uft.find(i) + 1).append("\n");
		}
		System.out.print(sb);
	}
	
	static class UnionFindTree {
	    int[] parents;
	    int[] counts;
	    
	    public UnionFindTree(int size) {
	        parents = new int[size];
	        counts = new int[size];
	        for (int i = 0; i < size; i++) {
	            parents[i] = i;
	            counts[i] = 1;
	        }
	    }
	    
	    public int find(int x) {
	        if (parents[x] == x) {
	            return x;
	        } else {
	            return parents[x] = find(parents[x]);
	        }
	    }
	    
	    public void unite(int x, int y) {
	        int xx = find(x);
	        int yy = find(y);
	        if (xx == yy) {
	            return;
	        }
	        if (counts[xx] > counts[yy] || (counts[xx] == counts[yy] && xx < yy)) {
	            parents[yy] = xx;
	            counts[xx] += counts[yy];
	        } else {
	            parents[xx] = yy;
	            counts[yy] += counts[xx];
	        }
	    }
	}
}
0