結果

問題 No.2316 Freight Train
ユーザー ks2mks2m
提出日時 2023-05-26 21:27:27
言語 Java21
(openjdk 21)
結果
AC  
実行時間 829 ms / 2,000 ms
コード長 1,607 bytes
コンパイル時間 1,752 ms
コンパイル使用メモリ 73,744 KB
実行使用メモリ 89,388 KB
最終ジャッジ日時 2023-08-26 10:15:27
合計ジャッジ時間 20,651 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 41 ms
49,768 KB
testcase_01 AC 41 ms
49,448 KB
testcase_02 AC 40 ms
49,508 KB
testcase_03 AC 777 ms
73,920 KB
testcase_04 AC 436 ms
65,068 KB
testcase_05 AC 380 ms
64,568 KB
testcase_06 AC 200 ms
56,080 KB
testcase_07 AC 488 ms
60,936 KB
testcase_08 AC 598 ms
74,848 KB
testcase_09 AC 488 ms
65,984 KB
testcase_10 AC 469 ms
64,904 KB
testcase_11 AC 556 ms
78,388 KB
testcase_12 AC 601 ms
71,748 KB
testcase_13 AC 784 ms
76,356 KB
testcase_14 AC 773 ms
74,528 KB
testcase_15 AC 818 ms
74,756 KB
testcase_16 AC 763 ms
74,860 KB
testcase_17 AC 791 ms
74,528 KB
testcase_18 AC 812 ms
75,412 KB
testcase_19 AC 803 ms
74,428 KB
testcase_20 AC 793 ms
75,040 KB
testcase_21 AC 791 ms
74,944 KB
testcase_22 AC 806 ms
75,148 KB
testcase_23 AC 766 ms
89,388 KB
testcase_24 AC 829 ms
82,004 KB
testcase_25 AC 585 ms
76,904 KB
testcase_26 AC 580 ms
76,032 KB
testcase_27 AC 366 ms
57,204 KB
testcase_28 AC 42 ms
49,372 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Main {
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] sa = br.readLine().split(" ");
		int n = Integer.parseInt(sa[0]);
		int q = Integer.parseInt(sa[1]);
		sa = br.readLine().split(" ");
		UnionFind uf = new UnionFind(n);
		for (int i = 0; i < n; i++) {
			int p = Integer.parseInt(sa[i]) - 1;
			if (p != -2) {
				uf.union(p, i);
			}
		}
		PrintWriter pw = new PrintWriter(System.out);
		for (int i = 0; i < q; i++) {
			sa = br.readLine().split(" ");
			int a = Integer.parseInt(sa[0]) - 1;
			int b = Integer.parseInt(sa[1]) - 1;
			if (uf.same(a, b)) {
				pw.println("Yes");
			} else {
				pw.println("No");
			}
		}
		pw.flush();
		br.close();
	}

	static class UnionFind {
		int[] parent, size;
		int num = 0; // 連結成分の数

		UnionFind(int n) {
			parent = new int[n];
			size = new int[n];
			num = n;
			for (int i = 0; i < n; i++) {
				parent[i] = i;
				size[i] = 1;
			}
		}

		void union(int x, int y) {
			int px = find(x);
			int py = find(y);
			if (px != py) {
				parent[px] = py;
				size[py] += size[px];
				num--;
			}
		}

		int find(int x) {
			if (parent[x] == x) {
				return x;
			}
			parent[x] = find(parent[x]);
			return parent[x];
		}

		/**
		 * xとyが同一連結成分か
		 */
		boolean same(int x, int y) {
			return find(x) == find(y);
		}

		/**
		 * xを含む連結成分のサイズ
		 */
		int size(int x) {
			return size[find(x)];
		}
	}
}
0