結果
問題 | No.1488 Max Score of the Tree |
ユーザー |
![]() |
提出日時 | 2021-05-07 09:05:31 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 299 ms / 2,000 ms |
コード長 | 2,481 bytes |
コンパイル時間 | 2,415 ms |
コンパイル使用メモリ | 78,620 KB |
実行使用メモリ | 90,068 KB |
最終ジャッジ日時 | 2024-09-14 22:12:57 |
合計ジャッジ時間 | 7,603 ms |
ジャッジサーバーID (参考情報) |
judge5 / judge6 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
import java.io.*; import java.util.*; public class Main { static ArrayList<ArrayList<Path>> graph = new ArrayList<>(); static ArrayList<Path> paths = new ArrayList<>(); static int total = 0; 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 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)); } getChildren(0, 0, 0); dp = new int[n - 1][k + 1]; System.out.println(dfw(n - 2, k) + total); } static int dfw(int idx, int cost) { if (cost < 0) { return Integer.MIN_VALUE; } if (idx < 0) { return 0; } if (dp[idx][cost] == 0) { Path p = paths.get(idx); dp[idx][cost] = Math.max(dfw(idx - 1, cost), dfw(idx - 1, cost - p.value) + p.count * p.value); } return dp[idx][cost]; } static int getChildren(int idx, int parent, int value) { int sum = 0; for (Path p : graph.get(idx)) { if (p.idx == parent) { continue; } p.count = getChildren(p.idx, idx, value + p.value); sum += p.count; paths.add(p); } if (sum == 0) { total += value; sum++; } return sum; } static class Path { int idx; int value; int count; 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 String next() throws Exception { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }