Rebuilding Roads
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 11626 | Accepted: 5337 |
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
题目大意:
有一个n个结点的树,问至少去掉几条边可以产生一个有p个节点的子树。
解题思路:
dp[i][j]表示以i号节点为根的子树,当有j个结点时最少需要去掉几条边。
初始化:当只有1个节点时,一定是连接它到孩子结点的所有边都去掉。
设某一孩子结点标号为v 则dp[i][j]=min(dp[i][j],dp[i][j-t]+dp[v][t]-1);
之所以要-1,因为背包的时候,都是拿这个儿子与前面儿子的最优值进行背包,这个儿子还没跟父亲连起来,相当于多砍了一刀
记录最小值是时,如果最小值在子树上需要加1,因为还有连接父亲结点的一条边没算。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 200;
int dp[maxn][maxn], book[maxn], n, m;
vector<int> p[maxn];
void dfs(int x)
{
dp[x][1] = p[x].size();
for(int i = 0; i < p[x].size(); i++)
{
int to = p[x][i];
dfs(to);
for(int v = m; v > 1; v--)
{
for(int k = 0; k < v; k++)
dp[x][v] = min(dp[x][v], dp[x][v-k]+dp[to][k]-1);
}
}
}
int main()
{
while(~scanf("%d%d", &n, &m))
{
int a, b, root;
memset(book, 0, sizeof(book));
memset(dp, 0x3f3f, sizeof(dp));
for(int i = 0; i < n; i++)
p[i].clear();
for(int i = 1; i < n; i++)
{
scanf("%d%d", &a, &b);
p[a].push_back(b);
book[b] = 1;
}
for(int i = 1; i <= n; i++)
{
if(!book[i])
{
root = i;
break;
}
}
dfs(root);
int ans = dp[root][m]; //除了根节点,其余每个节点都要多砍一刀
for(int i = 1; i <= n; i++)
{
if(i == root) continue;
ans = min(ans, dp[i][m]+1);
}
printf("%d\n", ans);
}
return 0;
}