結果
問題 | No.1488 Max Score of the Tree |
ユーザー |
![]() |
提出日時 | 2021-04-23 22:02:18 |
言語 | Java (openjdk 23) |
結果 |
AC
|
実行時間 | 348 ms / 2,000 ms |
コード長 | 1,500 bytes |
コンパイル時間 | 2,565 ms |
コンパイル使用メモリ | 78,032 KB |
実行使用メモリ | 121,252 KB |
最終ジャッジ日時 | 2024-07-04 08:02:10 |
合計ジャッジ時間 | 10,725 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
import java.util.ArrayList;import java.util.List;import java.util.Scanner;public class Main {static List<List<Hen>> list;public static void main(String[] args) throws Exception {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int k = sc.nextInt();list = new ArrayList<>(n);for (int i = 0; i < n; i++) {list.add(new ArrayList<>());}Hen[] arr = new Hen[n - 1];for (int i = 0; i < n - 1; i++) {Hen h = new Hen();h.a = sc.nextInt() - 1;h.b = sc.nextInt() - 1;h.c = sc.nextInt();list.get(h.a).add(h);list.get(h.b).add(h);arr[i] = h;}sc.close();dfs(0, -1);long[][] dp = new long[n][k + 1];for (int i = 0; i < n - 1; i++) {for (int j = 0; j <= k; j++) {dp[i + 1][j] = dp[i][j];}for (int j = 0; j <= k; j++) {int j2 = j + arr[i].c;if (j2 <= k) {dp[i + 1][j2] = Math.max(dp[i + 1][j2], dp[i][j] + arr[i].c * arr[i].d);} else {break;}}}long sum = 0;for (int i = 0; i < n - 1; i++) {sum += arr[i].c * arr[i].d;}long max = 0;for (int i = 0; i <= k; i++) {max = Math.max(max, dp[n - 1][i]);}System.out.println(sum + max);}static class Hen {int a, b, c, d;}static int dfs(int x, int p) {int ret = 0;if (list.get(x).size() == 1) {ret = 1;}for (Hen h : list.get(x)) {int nx = h.a;if (nx == x) {nx = h.b;}if (nx != p) {h.d = dfs(nx, x);ret += h.d;}}return ret;}}