結果
| 問題 |
No.2290 UnUnion Find
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-05-06 12:25:19 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 491 ms / 2,000 ms |
| コード長 | 1,603 bytes |
| コンパイル時間 | 2,134 ms |
| コンパイル使用メモリ | 77,656 KB |
| 実行使用メモリ | 48,912 KB |
| 最終ジャッジ日時 | 2024-11-23 21:13:44 |
| 合計ジャッジ時間 | 27,096 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 46 |
ソースコード
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
class Main{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
int N = Integer.parseInt(str[0]);
int Q = Integer.parseInt(str[1]);
UnionFind uf = new UnionFind(N+1);
StringBuilder answer = new StringBuilder();
while(Q-->0){
str = br.readLine().split(" ");
int q = Integer.parseInt(str[0]);
if(q==1){
int u = Integer.parseInt(str[1]);
int v = Integer.parseInt(str[2]);
uf.unite(u,v);
}
else{
int v = Integer.parseInt(str[1]);
int ans = uf.unUnitePoint(v);
answer.append(ans>N?-1:ans);
answer.append('\n');
}
}
System.out.println(answer.toString());
}
}
class UnionFind{
int N;
int[] par,unUnite,size;
UnionFind(int N){
this.N = 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 temp = rootX;
rootX = rootY;
rootY = temp;
}
par[rootY] = rootX;
size[rootX] += size[rootY];
int max = Math.max(unUnite[rootX],unUnite[rootY]);
while(max<N&&root(max)==rootX)max++;
unUnite[rootX] = max;
}
int unUnitePoint(int x){
return unUnite[root(x)];
}
}