結果
問題 |
No.1094 木登り / Climbing tree
|
ユーザー |
![]() |
提出日時 | 2022-04-07 14:13:22 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 1,658 ms / 2,000 ms |
コード長 | 3,123 bytes |
コンパイル時間 | 4,516 ms |
コンパイル使用メモリ | 79,004 KB |
実行使用メモリ | 125,156 KB |
最終ジャッジ日時 | 2024-11-08 07:26:35 |
合計ジャッジ時間 | 41,169 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 26 |
ソースコード
import java.io.*; import java.util.*; public class Main { static ArrayList<ArrayList<Path>> graph = new ArrayList<>(); static int[] depth; static int[][] parents; static int[] costs; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(); int n = sc.nextInt(); for (int i = 0; i < n; i++) { graph.add(new ArrayList<>()); } 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).add(new Path(b, c)); graph.get(b).add(new Path(a, c)); } depth = new int[n]; parents = new int[18][n]; costs = new int[n]; setDepth(0, 0, 0, 0); for (int i = 1; i < 18; 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[b] - costs[lca] * 2).append("\n"); } System.out.print(sb); } static int getLCA(int left, int right) { if (depth[left] < depth[right]) { return getLCA(right, left); } for (int i = 17; i >= 0; i--) { if (depth[left] - depth[right] >= (1 << i)) { left = parents[i][left]; } } if (left == right) { return left; } for (int i = 17; i >= 0; i--) { if (parents[i][left] != parents[i][right]) { left = parents[i][left]; right = parents[i][right]; } } return parents[0][left]; } static void setDepth(int idx, int p, int d, int c) { depth[idx] = d; parents[0][idx] = p; costs[idx] = c; for (Path x : graph.get(idx)) { if (x.idx == p) { continue; } setDepth(x.idx, idx, d + 1, c + x.value); } } static class Path { int idx; int value; public Path(int idx, int value) { this.idx = idx; this.value = value; } } } class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); 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 { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }