From ce02e8de140eab61b96b094e257eb35659d3c502 Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Sat, 11 Jun 2022 18:35:30 +0800 Subject: [PATCH] =?UTF-8?q?P3177=20[HAOI2015]=20=E6=A0=91=E4=B8=8A?= =?UTF-8?q?=E6=9F=93=E8=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/77254489 --- Luogu/P3177/P3177.cpp | 65 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Luogu/P3177/P3177.cpp diff --git a/Luogu/P3177/P3177.cpp b/Luogu/P3177/P3177.cpp new file mode 100644 index 00000000..f20dc83a --- /dev/null +++ b/Luogu/P3177/P3177.cpp @@ -0,0 +1,65 @@ +#include +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 2005; + +int n, k, fa[N], siz[N]; +long long f[N][N]; +std::vector> g[N]; + +void dfs(int u, int fa) { + siz[u] = 1; + f[u][0] = f[u][1] = 0; + + for (auto e : g[u]) { + int v = e.first, + w = e.second; + + if (v == fa) continue; + + dfs(v, u); + + siz[u] += siz[v]; + + for (int i = std::min(k, siz[u]); ~i; i--) { + if (~f[u][i]) { + f[u][i] += f[v][0] + 1ll * siz[v] * (n - k - siz[v]) * w; + } + + for (int j = std::min(i, siz[v]); j; j--) { + if (~f[u][i - j]) { + f[u][i] = std::max(f[u][i], f[u][i - j] + f[v][j] + 1ll * (j * (k - j) + (siz[v] - j) * (n - k - siz[v] + j)) * w); + } + } + } + } +} + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n >> k; + + k = std::max(k, n - k); + + for (int i = 1, u, v, w; i < n; i++) { + cin >> u >> v >> w; + + g[u].push_back(std::make_pair(v, w)); + g[v].push_back(std::make_pair(u, w)); + } + + memset(f, 0xff, sizeof(f)); + + dfs(1, 0); + + cout << f[1][k] << endl; + + return 0; +}