Rebuilding Roads
Description
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.
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.
Input
* 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.
* 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.
Output
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.
Sample Input
11 6 1 2 1 3 1 4 1 5 2 6 2 7 2 8 4 9 4 10 4 11
Sample Output
2
Hint
[A subtree with nodes (1, 2, 3, 6, 7, 8) will become isolated if roads 1-4 and 1-5 are destroyed.]
Source
题目大意:
在给定的树中,找出一颗恰为P个节点的子树,最少需要去除几条边。
解题思路:
树形DP,dp[i][j]表示以i节点为根,恰有j个节点时,需要去除几条边。
dp[father][i+j] = min(dp[father][i+j], dp[father][i] + dp[child[father][k]][j] - 2);
dp[father][1] = child[father].size() + 1;
dp[root][1] = child[root].size();
参考代码:
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int MAXN = 160;
const int INF = 0x3f3f3f3f;
int n, p, dp[MAXN][MAXN], root, ans;
bool isRoot[MAXN];
vector<int> child[MAXN];
void init() {
memset(dp, 0x3f, sizeof(dp));
for (int i = 0; i < n; i++) {
child[i].clear();
}
memset(isRoot, true, sizeof(isRoot));
ans = INF;
}
void input() {
for (int i = 0; i < n-1; i++) {
int a, b;
cin >> a >> b;
child[a].push_back(b);
isRoot[b] = false;
}
for (int i = 1; i <= n; i++) {
if (isRoot[i]) {
root = i;
break;
}
}
}
void dfs(int x) {
for (int i = 0; i < child[x].size(); i++) {
dfs(child[x][i]);
}
for (int s = 0; s < child[x].size(); s++) {
for (int i = p; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
dp[x][i] = min(dp[x][i-j] + dp[child[x][s]][j] - 2, dp[x][i]);
}
}
}
}
void work() {
for (int i = 0; i <= n; i++) {
dp[i][1] = child[i].size() + 1;
}
dp[root][1] = child[root].size();
dfs(root);
for (int i = 1; i <= n; i++) {
ans = min(ans, dp[i][p]);
}
}
void output() {
cout << ans << endl;
}
int main() {
ios::sync_with_stdio(false);
while (cin >> n >> p) {
init();
input();
work();
output();
}
return 0;
}