結果
問題 |
No.1488 Max Score of the Tree
|
ユーザー |
![]() |
提出日時 | 2021-04-23 21:58:30 |
言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 73 ms / 2,000 ms |
コード長 | 1,718 bytes |
コンパイル時間 | 941 ms |
コンパイル使用メモリ | 92,756 KB |
実行使用メモリ | 6,944 KB |
最終ジャッジ日時 | 2024-07-04 07:58:50 |
合計ジャッジ時間 | 2,945 ms |
ジャッジサーバーID (参考情報) |
judge1 / judge4 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 29 |
ソースコード
#include <iostream> #include <string> #include <algorithm> #include <utility> #include <cmath> #include <cstdlib> #include <map> #include <set> #include <queue> #include <vector> using namespace std; #define PAIR pair<long long, long long> #define m_p make_pair using Graph = vector<vector<PAIR>>; long long N, K; vector<int> depth; vector<int> subtree_size; vector<long long> dp; long long sum = 0; void dfs(const Graph& G, int v, int p, int d) { depth[v] = d; int count = 0; for (auto nv : G[v]) { if (nv.first == p) continue; count++; dfs(G, nv.first, v, d + 1); } subtree_size[v] = 1; if (count > 0) subtree_size[v] = 0; for (auto c : G[v]) { if (c.first == p) continue; subtree_size[v] += subtree_size[c.first]; } vector<long long> dp_(K + 1, 0); for (auto c : G[v]) { if (c.first == p) { long long a = c.second; for (int i = 0; i <= K; i++) { if (i + a < K + 1) dp_[i + a] = max(dp[i + a] + a * subtree_size[v], dp[i] + 2 * a * subtree_size[v]); else dp_[(i + a) % (K + 1)] = dp[(i + a) % (K + 1)] + a * subtree_size[v]; } } } if (v != 0) for (int i = 0; i <= K; i++) dp[i] = dp_[i]; } int main() { cin >> N >> K; Graph G(N); for (int i = 0; i < N - 1; i++) { long long a, b, c; cin >> a >> b >> c; G[a - 1].push_back(m_p(b - 1, c)); G[b - 1].push_back(m_p(a - 1, c)); } depth.assign(N, 0); subtree_size.assign(N, 0); dp.assign(K + 1, 0); dfs(G, 0, -1, 0); long long max_ = 0; for (int i = 0; i < K + 1; i++) max_ = max(max_, dp[i]); cout << max_ << endl; }