結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
htensai
|
| 提出日時 | 2020-05-26 13:02:57 |
| 言語 | Java (openjdk 23) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 1,856 bytes |
| コンパイル時間 | 1,926 ms |
| コンパイル使用メモリ | 77,256 KB |
| 実行使用メモリ | 76,200 KB |
| 最終ジャッジ日時 | 2024-10-13 02:38:16 |
| 合計ジャッジ時間 | 16,229 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | WA * 3 |
| other | WA * 8 |
ソースコード
import java.util.*;
public class Main {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
UnionFindTree uft = new UnionFindTree(n);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
int type = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
if (type == 1) {
uft.unite(a - 1, b - 1);
} else if (type == 2) {
uft.add(a - 1, b);
} else {
sb.append(uft.get(a - 1)).append("\n");
}
}
System.out.println(sb);
}
static class UnionFindTree {
int[] parents;
int[] ranks;
int[] points;
public UnionFindTree(int size) {
parents = new int[size];
ranks = new int[size];
points = new int[size];
for (int i = 0; i < size; i++) {
parents[i] = i;
}
}
public int find(int x) {
if (parents[x] == x) {
return x;
} else {
return find(parents[x]);
}
}
public void unite(int x, int y) {
int xx = find(x);
int yy = find(y);
if (xx == yy) {
return;
}
if (ranks[xx] < ranks[yy]) {
parents[xx] = yy;
points[xx] -= points[yy];
ranks[yy] = Math.max(ranks[yy], ranks[xx] + 1);
} else {
parents[yy] = xx;
points[yy] -= points[xx];
ranks[xx] = Math.max(ranks[xx], ranks[yy] + 1);
}
}
public void add(int x, int value) {
points[find(x)] += value;
}
public int get(int x) {
if (parents[x] == x) {
return points[x];
} else {
return points[x] + get(parents[x]);
}
}
}
}
htensai