結果
問題 | No.399 動的な領主 |
ユーザー | tenten |
提出日時 | 2021-03-04 14:33:59 |
言語 | Java21 (openjdk 21) |
結果 |
AC
|
実行時間 | 1,981 ms / 2,000 ms |
コード長 | 2,569 bytes |
コンパイル時間 | 2,343 ms |
コンパイル使用メモリ | 79,952 KB |
実行使用メモリ | 112,896 KB |
最終ジャッジ日時 | 2024-04-15 06:58:20 |
合計ジャッジ時間 | 25,138 ms |
ジャッジサーバーID (参考情報) |
judge4 / judge5 |
(要ログイン)
テストケース
テストケース表示入力 | 結果 | 実行時間 実行使用メモリ |
---|---|---|
testcase_00 | AC | 135 ms
41,828 KB |
testcase_01 | AC | 132 ms
41,892 KB |
testcase_02 | AC | 171 ms
42,248 KB |
testcase_03 | AC | 162 ms
41,772 KB |
testcase_04 | AC | 225 ms
46,380 KB |
testcase_05 | AC | 483 ms
50,768 KB |
testcase_06 | AC | 1,981 ms
109,948 KB |
testcase_07 | AC | 1,946 ms
105,896 KB |
testcase_08 | AC | 1,667 ms
94,568 KB |
testcase_09 | AC | 1,843 ms
106,704 KB |
testcase_10 | AC | 237 ms
49,612 KB |
testcase_11 | AC | 468 ms
51,348 KB |
testcase_12 | AC | 1,675 ms
97,188 KB |
testcase_13 | AC | 1,770 ms
92,008 KB |
testcase_14 | AC | 1,285 ms
112,024 KB |
testcase_15 | AC | 1,342 ms
112,896 KB |
testcase_16 | AC | 1,416 ms
104,308 KB |
testcase_17 | AC | 1,577 ms
93,592 KB |
testcase_18 | AC | 1,899 ms
102,408 KB |
ソースコード
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); } } }