結果
問題 | No.2290 UnUnion Find |
ユーザー |
![]() |
提出日時 | 2023-05-06 11:46:08 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 1,918 ms / 2,000 ms |
コード長 | 1,706 bytes |
コンパイル時間 | 3,003 ms |
コンパイル使用メモリ | 76,956 KB |
実行使用メモリ | 61,244 KB |
最終ジャッジ日時 | 2024-11-23 20:54:07 |
合計ジャッジ時間 | 85,795 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 46 |
ソースコード
import java.util.Scanner;import java.util.Arrays;class Main {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int N = sc.nextInt();int Q = sc.nextInt();UnionFind uf = new UnionFind(N + 1);while (Q-- > 0) {int q = sc.nextInt();if (q == 1) {int u = sc.nextInt();int v = sc.nextInt();uf.unite(u, v);} else {int v = sc.nextInt();int ans = uf.unUnitePoint(v);if (ans > N)ans = -1;System.out.println(ans);}}}}class UnionFind {int[] par, unUnite, size;UnionFind(int N) {par = new int[N];unUnite = new int[N];size = new int[N];Arrays.fill(par, -1);Arrays.fill(unUnite, 1);Arrays.fill(size, 1);unUnite[1] = 2;}int root(int x) {if (par[x] == -1)return x;return par[x] = root(par[x]);}void unite(int x, int y) {int rootX = root(x);int rootY = root(y);if (rootX == rootY)return;if (size[rootX] < size[rootY]) {int tmp = rootX;rootX = rootY;rootY = tmp;}par[rootY] = rootX;size[rootX] += size[rootY];check(rootY);check(rootX);}void check(int x) {int root = root(x);while (unUnite[root] < unUnite.length && root == root(unUnite[root]))unUnite[root]++;}int unUnitePoint(int x) {return unUnite[root(x)];}}