Rebuilding Roads
链接:https://ac.nowcoder.com/acm/problem/106544
来源:牛客网
题目描述:
The cows have reconstructed Farmer John’s farm, with its N barns (1 <= N <= 150, number 1…N) after the terrible earthquake last May. The cows didn’t have time to rebuild any extra roads, so now there is exactly one way to get from any given barn to any other barn. Thus, the farm transportation system can be represented as a tree.
Farmer John wants to know how much damage another earthquake could do. He wants to know the minimum number of roads whose destruction would isolate a subtree of exactly P (1 <= P <= N) barns from the rest of the barns.
输入描述:
- Line 1: Two integers, N and P
- Lines 2…N: N-1 lines, each with two integers I and J. Node I is node J’s parent in the tree of roads.
输出描述:
A single line containing the integer that is the minimum number of roads that need to be destroyed for a subtree of P nodes to be isolated.
#include <bits/stdc++.h>
using namespace std;
const int maxn = 205;
int dp[maxn][maxn];
vector<int> tree[maxn];
void dfs(int pos, int p)
{
for (int i = 0; i < tree[pos].size(); i++)
{
dfs(tree[pos][i], p);
for (int j = p; j >= 1; j--)
for (int k = 1; k < j; k++)
dp[pos][j] = min(dp[pos][j - k] + dp[tree[pos][i]][k] - 1, dp[pos][j]);
}
}
int main()
{
for (int i = 0; i < maxn; i++)
for (int j = 0; j < maxn; j++)
dp[i][j] = maxn;
int n, p;
cin >> n >> p;
int u, v;
while (cin >> u >> v)
tree[u].push_back(v);
for (int i = 1; i <= n; i++)
dp[i][1] = tree[i].size();
dfs(1, p);
int ans = dp[1][p];
for (int i = 2; i <= n; i++)
ans = min(ans, dp[i][p] + 1);
cout << ans << endl;
return 0;
}