結果

問題 No.1488 Max Score of the Tree
ユーザー ks2mks2m
提出日時 2021-04-23 22:02:18
言語 Java21
(openjdk 21)
結果
AC  
実行時間 355 ms / 2,000 ms
コード長 1,500 bytes
コンパイル時間 2,235 ms
コンパイル使用メモリ 74,996 KB
実行使用メモリ 135,968 KB
最終ジャッジ日時 2023-09-17 12:14:44
合計ジャッジ時間 11,527 ms
ジャッジサーバーID
(参考情報)
judge13 / judge15
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 352 ms
129,964 KB
testcase_01 AC 353 ms
127,540 KB
testcase_02 AC 337 ms
131,692 KB
testcase_03 AC 335 ms
134,276 KB
testcase_04 AC 355 ms
133,388 KB
testcase_05 AC 145 ms
55,728 KB
testcase_06 AC 270 ms
78,240 KB
testcase_07 AC 302 ms
108,836 KB
testcase_08 AC 207 ms
84,768 KB
testcase_09 AC 269 ms
78,684 KB
testcase_10 AC 309 ms
108,544 KB
testcase_11 AC 345 ms
133,972 KB
testcase_12 AC 133 ms
56,012 KB
testcase_13 AC 195 ms
67,796 KB
testcase_14 AC 245 ms
92,332 KB
testcase_15 AC 197 ms
78,052 KB
testcase_16 AC 169 ms
60,764 KB
testcase_17 AC 173 ms
67,560 KB
testcase_18 AC 243 ms
112,244 KB
testcase_19 AC 277 ms
85,144 KB
testcase_20 AC 234 ms
67,596 KB
testcase_21 AC 194 ms
61,208 KB
testcase_22 AC 240 ms
77,452 KB
testcase_23 AC 124 ms
56,152 KB
testcase_24 AC 128 ms
55,568 KB
testcase_25 AC 129 ms
55,828 KB
testcase_26 AC 240 ms
77,972 KB
testcase_27 AC 163 ms
58,112 KB
testcase_28 AC 200 ms
65,576 KB
testcase_29 AC 213 ms
68,048 KB
testcase_30 AC 336 ms
117,992 KB
testcase_31 AC 338 ms
135,968 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

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;
	}
}
0