結果
問題 | No.399 動的な領主 |
ユーザー |
![]() |
提出日時 | 2021-03-04 14:33:59 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 1,513 ms / 2,000 ms |
コード長 | 2,569 bytes |
コンパイル時間 | 1,970 ms |
コンパイル使用メモリ | 79,860 KB |
実行使用メモリ | 110,904 KB |
最終ジャッジ日時 | 2024-10-04 21:10:41 |
合計ジャッジ時間 | 20,591 ms |
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
other | AC * 19 |
ソースコード
import java.util.*; public class Main { static ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); static int[] depth; static int[] points; static int[][] parents; 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 ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; graph.get(a).add(b); graph.get(b).add(a); } depth = new int[n]; points = new int[n]; parents = new int[30][n]; setDepth(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(); for (int i = 0; i < q; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; int lca = getLCA(a, b); points[a]++; points[b]++; points[lca]--; if (lca != 0) { points[parents[0][lca]]--; } } getPoint(0, 0); long ans = 0; for (int x : points) { ans += (long)x * (x + 1) / 2; } System.out.println(ans); } static int getLCA(int left, int right) { if (depth[left] < depth[right]) { return getLCA(right, left); } for (int i = 29; i >= 0 && depth[left] > depth[right]; i--) { if (depth[left] - depth[right] >= (1 << i)) { left = parents[i][left]; } } if (left == right) { return left; } for (int i = 29; i >= 0; i--) { if (parents[i][left] == parents[i][right]) { continue; } left = parents[i][left]; right = parents[i][right]; } return parents[0][left]; } static int getPoint(int idx, int p) { for (int x : graph.get(idx)) { if (x == p) { continue; } points[idx] += getPoint(x, idx); } return points[idx]; } static void setDepth(int idx, int d, int p) { depth[idx] = d; parents[0][idx] = p; for (int x : graph.get(idx)) { if (x == p) { continue; } setDepth(x, d + 1, idx); } } }