結果
| 問題 | No.1488 Max Score of the Tree |
| コンテスト | |
| ユーザー |
tabae326
|
| 提出日時 | 2021-04-23 22:11:04 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.89.0) |
| 結果 |
AC
|
| 実行時間 | 162 ms / 2,000 ms |
| コード長 | 1,704 bytes |
| 記録 | |
| コンパイル時間 | 3,457 ms |
| コンパイル使用メモリ | 208,848 KB |
| 最終ジャッジ日時 | 2025-01-20 23:57:24 |
|
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 29 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, srt, end) for (long long i = (srt); i < (long long)(end); i++)
using pl = pair<ll,ll>;
using tl = tuple<ll,ll,ll>;
void chmax(ll &a, ll b) {
a = max(a, b);
}
void solve() {
ll n, k;
cin >> n >> k;
vector<vector<tl>> G(n);
vector<ll> weight(n-1);
rep(i, 0, n-1) {
ll u, v, w;
cin >> u >> v >> w;
u--; v--;
G[u].push_back({v, w, i});
G[v].push_back({u, w, i});
weight[i] = w;
}
vector<ll> cnt(n-1, 0), sub(n, 0);
auto dfs1 = [&](auto dfs1, ll cur, ll par) -> ll {
ll res = 0;
bool leaf = true;
for(auto [to, cost, id] : G[cur]) {
if(to == par) continue;
leaf = false;
res += dfs1(dfs1, to, cur);
cnt[id] += sub[to];
}
if(leaf) res = 1;
sub[cur] = res;
return res;
};
dfs1(dfs1, 0, -1);
vector<ll> depth(n, 0);
ll sum = 0;
auto dfs2 = [&](auto dfs2, ll cur, ll par) -> void {
bool leaf = true;
for(auto [to, cost, id] : G[cur]) {
if(to == par) continue;
leaf = false;
depth[to] = depth[cur] + cost;
dfs2(dfs2, to, cur);
}
if(leaf) sum += depth[cur];
};
dfs2(dfs2, 0, -1);
vector dp(n+10, vector<ll>(k+100, 0));
rep(i, 0, n-1) {
rep(j, 0, k+1) chmax(dp[i+1][j], dp[i][j]);
rep(j, 0, k) if(j+weight[i] <= k) chmax(dp[i+1][j+weight[i]], dp[i][j]+cnt[i]*weight[i]);
}
ll ans = 0;
rep(i, 0, k+1) chmax(ans, dp[n-1][i]);
cout << sum+ans << endl;
}
int main() {
solve();
return 0;
}
tabae326