結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
tenten
|
| 提出日時 | 2022-08-30 15:55:24 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 707 ms / 2,000 ms |
| コード長 | 2,820 bytes |
| コンパイル時間 | 2,381 ms |
| コンパイル使用メモリ | 78,804 KB |
| 実行使用メモリ | 71,132 KB |
| 最終ジャッジ日時 | 2024-11-07 10:25:26 |
| 合計ジャッジ時間 | 9,858 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 8 |
ソースコード
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner();
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.getValue(a - 1)).append("\n");
}
}
System.out.print(sb);
}
static class UnionFindTree {
int[] parents;
int[] values;
public UnionFindTree(int size) {
parents = new int[size];
values = new int[size];
for (int i = 0; i < size; i++) {
parents[i] = i;
}
}
public int find(int x) {
if (x == parents[x]) {
return x;
} else {
int p = find(parents[x]);
if (p != parents[x]) {
values[x] += values[parents[x]];
}
return parents[x] = p;
}
}
public boolean same(int x, int y) {
return find(x) == find(y);
}
public void unite(int x, int y) {
int xx = find(x);
int yy = find(y);
if (xx == yy) {
return;
}
parents[xx] = yy;
values[xx] -= values[yy];
}
public void add(int idx, int v) {
values[find(idx)] += v;
}
public int getValue(int idx) {
int p = find(idx);
if (p == idx) {
return values[p];
} else {
return values[p] + values[idx];
}
}
}
}
class Scanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
StringBuilder sb = new StringBuilder();
public Scanner() throws Exception {
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
public String next() throws Exception {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
tenten