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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <algorithm> #include <map> #include <set> #include <queue> #include <stack> #include <cctype> using namespace std; struct ege { int to, nex; } edge[305]; int head[155], sum[155], tot, dp[155][155], n, p; void addedge(int from, int to) { edge[tot].nex = head[from]; edge[tot].to = to; head[from] = tot++; } int countsum(int root, int pre) { sum[root] = 1; for (int i = head[root]; i; i = edge[i].nex) { if (edge[i].to != pre) sum[root] += countsum(edge[i].to, root); } return sum[root]; } void init() { for (int i = 0; i <= n; i++) sum[i] = 0; for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) dp[i][j] = 1e9; } } void dfs(int root, int pre) { dp[root][0] = 0; dp[root][sum[root]] = 1; int i, j, k; for (i = head[root]; i; i = edge[i].nex) { if (edge[i].to != pre) { dfs(edge[i].to, root); for (j = sum[root]; j > 0; j--) { for (k = 1; k <= sum[edge[i].to] && k <= j; k++) dp[root][j] = min(dp[root][j], dp[root][j - k] + dp[edge[i].to][k]); } } } } int main() { while (~scanf("%d%d", &n, &p)) { init(); tot = 1; int i, j, u, v, res = 1e9; for (i = 0; i <= n; i++) head[i] = 0; for (i = 1; i < n; i++) { scanf("%d%d", &u, &v); addedge(u, v); addedge(v, u); } for (i = 1; i <= n; i++) { init(); countsum(i, -1); dfs(i, -1); if (dp[i][n - p] < res) res = dp[i][n - p]; } printf("%d\n", res); } return 0; }
|