結果
| 問題 |
No.898 tri-βutree
|
| コンテスト | |
| ユーザー |
htensai
|
| 提出日時 | 2020-06-10 20:00:35 |
| 言語 | Java (openjdk 23) |
| 結果 |
WA
|
| 実行時間 | - |
| コード長 | 2,244 bytes |
| コンパイル時間 | 2,432 ms |
| コンパイル使用メモリ | 80,980 KB |
| 実行使用メモリ | 142,716 KB |
| 最終ジャッジ日時 | 2024-06-23 14:39:13 |
| 合計ジャッジ時間 | 43,787 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 1 WA * 20 |
ソースコード
import java.util.*;
public class Main {
static int[][] parents;
static long[] dists;
static int[] depth;
static ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>();
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
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 c = sc.nextInt();
graph.get(a).put(b, c);
graph.get(b).put(a, c);
}
parents = new int[n][18];
dists = new long[n];
depth = new int[n];
setParent(0, 0, 0, 0);
for (int i = 1; i < 18; i++) {
for (int j = 0; j < n; j++) {
parents[j][i] = parents[parents[j][i - 1]][i - 1];
}
}
int q = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < q; i++) {
sb.append(getValue(sc.nextInt(), sc.nextInt(), sc.nextInt())).append("\n");
}
System.out.print(sb);
}
static void setParent(int idx, int parent, int value, int dep) {
parents[idx][0] = parent;
dists[idx] = value;
depth[idx] = dep;
for (Map.Entry<Integer, Integer> entry : graph.get(idx).entrySet()) {
if (entry.getKey() == parent) {
continue;
}
setParent(entry.getKey(), idx, value + entry.getValue(), dep + 1);
}
}
static long getValue(int a, int b, int c) {
return (getValue(a, b) + getValue(b, c) + getValue(c, a)) / 2;
}
static long getValue(int a, int b) {
int c = getLCA(a, b);
return dists[a] + dists[b] - dists[c] * 2;
}
static int getLCA(int a, int b) {
if (depth[a] > depth[b]) {
return getLCA(b, a);
}
for (int i = 17; i >= 0 && depth[a] < depth[b]; i--) {
if (depth[b] - depth[a] >= (1 << i)) {
b = parents[b][i];
}
}
for (int i = 17; i >= 0 && a != b; i--) {
if (parents[a][i] != parents[b][i]) {
a = parents[a][i];
b = parents[b][i];
}
}
if (a != b) {
a = parents[a][0];
b = parents[b][0];
}
return a;
}
}
htensai