結果
| 問題 |
No.898 tri-βutree
|
| コンテスト | |
| ユーザー |
tenten
|
| 提出日時 | 2020-10-20 17:50:55 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 2,283 ms / 4,000 ms |
| コード長 | 2,486 bytes |
| コンパイル時間 | 3,589 ms |
| コンパイル使用メモリ | 79,636 KB |
| 実行使用メモリ | 135,968 KB |
| 最終ジャッジ日時 | 2024-11-08 23:51:58 |
| 合計ジャッジ時間 | 43,030 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 21 |
ソースコード
import java.util.*;
public class Main {
static int[][] parents;
static int[] depth;
static long[] weights;
static ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
parents = new int[30][n];
depth = new int[n];
weights = new long[n];
for (int i = 0; i < n; i++) {
graph.add(new HashMap<>());
}
for (int i = 0; i < n - 1; i ++) {
int a = sc.nextInt();
int b = sc.nextInt();
int w = sc.nextInt();
graph.get(a).put(b, w);
graph.get(b).put(a, w);
}
setDepth(0, 0, 0, 0);
for (int i = 1; i < 30; i++) {
for (int j = 0; j < n; j++) {
parents[i][j] = parents[i - 1][parents[i - 1][j]];
}
}
int q = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int cc = getLCA(a, b);
int aa = getLCA(b, c);
int bb = getLCA(c, a);
long ans = weights[a] + weights[b] + weights[c] - weights[aa] - weights[bb] - weights[cc];
sb.append(ans).append("\n");
}
System.out.print(sb);
}
static int getLCA(int a, int b) {
if (depth[a] < depth[b]) {
return getLCA(b, a);
}
int diff = depth[a] - depth[b];
for (int i = 29; i >= 0 && diff > 0; i--) {
if (diff < (1 << i)) {
continue;
}
a = parents[i][a];
diff = depth[a] - depth[b];
}
if (a == b) {
return a;
}
for (int i = 29; i >= 0; i--) {
if (parents[i][a] != parents[i][b]) {
a = parents[i][a];
b = parents[i][b];
}
}
return parents[0][a];
}
static void setDepth(int idx, int parent, int d, long w) {
parents[0][idx] = parent;
depth[idx] = d;
weights[idx] = w;
for (Map.Entry<Integer, Integer> entry : graph.get(idx).entrySet()) {
if (entry.getKey() == parent) {
continue;
}
setDepth(entry.getKey(), idx, d + 1, w + entry.getValue());
}
}
}
tenten