結果
問題 |
No.1094 木登り / Climbing tree
|
ユーザー |
![]() |
提出日時 | 2021-03-12 08:17:57 |
言語 | Java (openjdk 23) |
結果 |
TLE
|
実行時間 | - |
コード長 | 2,075 bytes |
コンパイル時間 | 2,669 ms |
コンパイル使用メモリ | 79,868 KB |
実行使用メモリ | 183,280 KB |
最終ジャッジ日時 | 2024-10-13 17:41:30 |
合計ジャッジ時間 | 10,487 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | TLE * 1 -- * 25 |
ソースコード
import java.util.*; public class Main { static ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>(); static int n; static int[][] parents; static int[] costs; static int[] depths; public static void main (String[] args) { Scanner sc = new Scanner(System.in); 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() - 1; int b = sc.nextInt() - 1; int c = sc.nextInt(); graph.get(a).put(b, c); graph.get(b).put(a, c); } parents = new int[20][n]; costs = new int[n]; depths = new int[n]; setDepth(0, 0, 0, 0); for (int i = 1; i < 20; 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() - 1; int b = sc.nextInt() - 1; int lca = getLCA(a, b); sb.append(costs[a] - costs[lca] * 2 + costs[b]).append("\n"); } System.out.print(sb); } static int getLCA(int a, int b) { if (depths[a] < depths[b]) { return getLCA(b, a); } for (int i = 19; i >= 0 && depths[a] > depths[b]; i--) { if (depths[a] - depths[b] >= (1 << i)) { a = parents[i][a]; } } if (a == b) { return a; } for (int i = 19; 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 p, int d, int c) { parents[0][idx] = p; costs[idx] = c; depths[idx] = d; for (int x : graph.get(idx).keySet()) { if (x == p) { continue; } setDepth(x, idx, d + 1, c + graph.get(idx).get(x)); } } }