結果
問題 | No.1488 Max Score of the Tree |
ユーザー |
![]() |
提出日時 | 2022-08-17 19:47:23 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 337 ms / 2,000 ms |
コード長 | 2,761 bytes |
コンパイル時間 | 2,721 ms |
コンパイル使用メモリ | 85,348 KB |
実行使用メモリ | 89,760 KB |
最終ジャッジ日時 | 2024-10-04 23:56:22 |
合計ジャッジ時間 | 8,081 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
import java.io.*;import java.util.*;public class Main {static ArrayList<HashMap<Integer, Integer>> graph = new ArrayList<>();static Node[] nodes;static int[][] dp;public static void main(String[] args) throws Exception {Scanner sc = new Scanner();int n = sc.nextInt();int k = sc.nextInt();for (int i = 0; i < n; i++) {graph.add(new HashMap<>());}nodes = new Node[n - 1];for (int i = 0; i < n - 1; i++) {nodes[i] = new Node(sc.nextInt() - 1, sc.nextInt() - 1, sc.nextInt());graph.get(nodes[i].left).put(nodes[i].right, i);graph.get(nodes[i].right).put(nodes[i].left, i);}setCounts(0, 0);dp = new int[n - 1][k + 1];System.out.println(dfw(n - 2, k));}static int setCounts(int idx, int p) {int count = 0;for (int x : graph.get(idx).keySet()) {if (x == p) {continue;}count += setCounts(x, idx);}if (count == 0) {count = 1;}if (idx != p) {nodes[graph.get(idx).get(p)].count = count;}return count;}static int dfw(int idx, int v) {if (v < 0) {return Integer.MIN_VALUE;}if (idx < 0) {return 0;}if (dp[idx][v] == 0) {dp[idx][v] = Math.max(dfw(idx - 1, v) + nodes[idx].getSum(), dfw(idx - 1, v - nodes[idx].score) + nodes[idx].getSum() * 2);}return dp[idx][v];}static class Node {int left;int right;int score;int count;public Node(int left, int right, int score) {this.left = left;this.right = right;this.score = score;}public int getSum() {return score * count;}public String toString() {return score + ":" + count;}}}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 {while (!st.hasMoreTokens()) {st = new StringTokenizer(br.readLine());}return st.nextToken();}}