Luogu P1272 重建道路

题目描述

https://www.luogu.com.cn/problem/P1272

Solution

我们令f[u][i]表示以u为根的大小为i的子树最少需要切掉几条边

转移类似背包

由于这个背包要求最小值,所以默认全切掉比较方便

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
#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 151
using namespace std;

int n, m;

struct Edge {
int to, next;
} e[maxn * 2]; int c1, head[maxn], du[maxn];
inline void add_edge(int u, int v) {
e[c1].to = v; e[c1].next = head[u]; head[u] = c1++;
}

int f[maxn][maxn], ans = maxn, sz[maxn];
void dfs(int u, int fa) {
sz[u] = 1; f[u][1] = du[u];
for (int i = head[u]; ~i; i = e[i].next) {
int v = e[i].to; if (v == fa) continue;
dfs(v, u); sz[u] += sz[v];
for (int j = sz[u]; j >= 2; --j)
for (int k = 1; k < j; ++k)
f[u][j] = min(f[u][j], f[u][j - k] + f[v][k] - 2);
}
ans = min(ans, f[u][m]);
}

int main() { memset(head, -1, sizeof head);
cin >> n >> m;
for (int i = 1; i < n; ++i) {
int x, y; cin >> x >> y;
add_edge(x, y); add_edge(y, x);
++du[x]; ++du[y];
}
memset(f, 10, sizeof f); dfs(1, 0);
cout << ans << endl;
return 0;
}