結果
問題 | No.1488 Max Score of the Tree |
ユーザー |
![]() |
提出日時 | 2021-04-23 22:44:13 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 243 ms / 2,000 ms |
コード長 | 3,150 bytes |
コンパイル時間 | 2,513 ms |
コンパイル使用メモリ | 216,600 KB |
最終ジャッジ日時 | 2025-01-21 00:14:29 |
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
#include <bits/stdc++.h>using namespace std;struct iofast_t {iofast_t() {ios::sync_with_stdio(false);cin.tie(nullptr); cout.tie(nullptr);}} iofast;struct uns_t {} uns;template <typename Element, typename Head, typename ...Args>auto vec(Element init, Head arg, Args ...args) {if constexpr (sizeof...(Args) == 0) return std::vector(arg, init);else return std::vector(arg, vec(init, args...));}template <typename Element, typename Head, typename ...Args>auto vec(uns_t, Head arg, Args ...args) {return vec(Element(), arg, args...);}template <typename T, typename Compare = less<T>>T &chmin(T &l, T r, Compare &&f = less<T>()) { return l = min(l, r, f); }template <typename T, typename Compare = less<T>>T &chmax(T &l, T r, Compare &&f = less<T>()) { return l = max(l, r, f); }int main() {#define int int64_tint n, k; cin >> n >> k;auto g = vec<tuple<int, int>>(uns, n, 0);auto e = vec<tuple<int, int, int>>(uns, n - 1);for (int i = 0; i < n - 1; ++i) {int a, b, c; cin >> a >> b >> c; --a; --b;g[a].emplace_back(b, c);g[b].emplace_back(a, c);e[i] = { a, b, c };}auto c = vec<int>(uns, n);auto d = vec<bool>(false, n, n);auto dfs = [&](int v, int p, auto &&dfs) -> int {auto &ans = c[v];ans = 0;for (auto [next, _] : g[v]) {if (next == p) continue;ans += dfs(next, v, dfs);d[v][next] = true;}ans += ans == 0;return ans;};dfs(0, -1, dfs);for (auto &[a, b, c] : e) {if (!d[a][b]) {swap(a, b);}}auto value = vec<int>(uns, n - 1);auto weight = vec<int>(uns, n - 1);for (int i = 0; i < n - 1; ++i) {auto [a, b, cost] = e[i];value[i] = cost * c[b];weight[i] = cost;}auto dp = vec<int64_t>(0, n, k + 1);auto prev = vec<tuple<int, int>>(uns, n, k + 1);for (int i = 1; i <= n - 1; ++i) {for (int j = 0; j <= k; ++j) {if (weight[i - 1] <= j) {if (auto v = dp[i - 1][j - weight[i - 1]] + value[i - 1]; dp[i][j] < v) {dp[i][j] = v;prev[i][j] = { i - 1, j - weight[i - 1] };}}if (dp[i][j] < dp[i - 1][j]) {dp[i][j] = dp[i - 1][j];prev[i][j] = { i - 1, j };}}}auto choosed = vec<tuple<int, int>>(uns, 0);auto back = [&](int i, int j, auto &&back) -> void {if (i == 0 && j == 0) return;auto [pi, pj] = prev[i][j];back(pi, pj, back);if (j != pj && weight[i - 1] <= j) {auto [a, b, c] = e[i - 1];choosed.emplace_back(a, b);}};back(n - 1, k, back);for (auto [a, b] : choosed) {for (auto &[c, d, cost] : e) {if (a == c && b == d) {cost *= 2;}}}int64_t ans = 0;for (auto [a, b, cost] : e) {ans += c[b] * cost;}cout << ans << endl;}