盒子
盒子
文章目录
  1. 题目
  2. 题意
  3. 思路
  4. 代码

HDU 5148 Cities(树dp)

题目

源地址:http://acm.hdu.edu.cn/showproblem.php?pid=5148

题意

给定一棵树,数的节点数为n。问从中选出K个点,使得这些点之间的距离和最小

思路

考虑每条边的贡献,一条边会把树分成两部分,若在其中一部分里选择了x个点,则这条边被统计的次数为x(K-x)2. 那么考虑dp[u][i]表示在u的子树中选择了i个点的最小代价,有转移dp[u][i] = min(dp[u][i-j]+ dp[v][j] + j(K-j)2*c)​​

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#define pb push_back
#define INF 1 << 30
#define fi first
#define se second
#define debug puts("=====================");
#define pii pair<int, int>
using namespace std;
typedef long long ll;
const int N = 2100;
int K, n;
vector< pii > g[N];
ll dp[N][55];
void change(ll &x, ll v) {
if (x == -1 || x > v) x = v;
}
void dfs(int u, int fa) {
dp[u][1] = 0;
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i].fi, c = g[u][i].se;
if (v == fa) continue;
dfs(v, u);
for (int j = K - 1; j >= 1; j--) {
if (dp[u][j] == -1) continue;
for (int k = 1; j + k <= K; k++) {
if (dp[v][k] == -1) continue;
change(dp[u][j + k], dp[u][j] + dp[v][k] + (ll)2 * k * (K - k) * c);
}
}
}
}
int main () {
int t, u, v, c;
scanf("%d", &t);
while(t--) {
scanf("%d%d", &n, &K);
for (int i = 1; i <= n; i++) {
g[i].clear();
for (int j = 0; j <= K; j++) dp[i][j] = -1;
}
for (int i = 1; i < n; i++) {
scanf("%d%d%d", &u, &v, &c);
g[u].pb({v, c});
g[v].pb({u, c});
}
dfs(1, -1);
ll ans = dp[1][K];
for (int i = 2; i <= n; i++) if (dp[i][K] != -1) ans = min(ans, dp[i][K]);
printf("%I64d\n", ans);
}
return 0;
}