結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
htensai
|
| 提出日時 | 2020-06-04 14:31:48 |
| 言語 | Java (openjdk 23) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 2,171 bytes |
| コンパイル時間 | 3,002 ms |
| コンパイル使用メモリ | 84,660 KB |
| 実行使用メモリ | 155,732 KB |
| 最終ジャッジ日時 | 2024-11-29 01:22:58 |
| 合計ジャッジ時間 | 24,223 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 3 TLE * 5 |
ソースコード
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();
if (type == 1) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
uft.unite(a, b);
} else if (type == 2) {
int a = sc.nextInt() - 1;
int b = sc.nextInt();
uft.add(a, b);
} else {
sb.append(uft.get(sc.nextInt() - 1)).append("\n");
sc.nextInt();
}
}
System.out.print(sb);
}
static class UnionFindTree {
int[] parents;
int[] points;
public UnionFindTree(int size) {
parents = 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;
}
int point = getPoint(parents[x]);
parents[x] = find(parents[x]);
points[x] = points[x] + point - points[parents[x]];
return parents[x];
}
public int getPoint(int x) {
if (parents[x] == x) {
return points[x];
} else {
return getPoint(parents[x]) + points[x];
}
}
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;
points[xx] -= points[yy];
}
public void add(int x, int value) {
points[find(x)] += value;
}
public int get(int x) {
int xx = find(x);
if (xx == x) {
return points[x];
} else {
return points[x] + points[xx];
}
}
public String toString() {
return Arrays.toString(parents) + Arrays.toString(points);
}
}
}
htensai