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.
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.
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
题意: 在一棵树结构上, 要求断开最少的边可以得到节点个数为P的子树.
解题思路:
1. 题目很简单, 可以使用线性dp的思路, 设状态dp[i][j]: 以i为根,保留j个节点的最小消耗.
易得动态方程: dp[i][j+k] = min(dp[i][j]+dp[ g[i][v] ][k]-2);
(g[i][v]:表示i的相邻节点v, 因为2棵子树要合并, 相邻边多删除了2次)
2. 初始化: 当i == root时: dp[i][1] = 相邻节点个数. (一个节点一条边)
否则: dp[i][1] = 相邻节点个数 + 一个父亲节点个数.
3. 递推的方向自下而上即可.
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 155
const int INF = (1<<29);
int n, p, root;
int g[MAX][MAX], num[MAX], flag[MAX];
int dp[MAX][MAX];
inline int min(int a, int b)
{
return a < b ? a : b;
}
void dfs(int u)
{
int i, j, k;
for(i = 0; i < num[u]; ++i)
dfs(g[u][i]);
if(u == root) dp[u][1] = num[u];
else dp[u][1] = num[u]+1;
for(i = 0; i < num[u]; ++i)
{
for(j = p-1; j >= 1; --j)
{
if(dp[u][j] < INF)
{
for(k = 1; j+k <= p; ++k)
{
if(dp[ g[u][i] ][k] < INF)
dp[u][j+k] = min(dp[u][j+k], dp[u][j]+dp[ g[u][i] ][k]-2);
}
}
}
}
}
int main()
{
// freopen("input.txt", "r", stdin);
int u, v, i, j;
while(scanf("%d %d",&n, &p) != EOF)
{
memset(num, 0, sizeof(num));
memset(flag, 0, sizeof(flag));
memset(g, 0, sizeof(g));
for(i = 0; i <= n; ++i)
for(j = 0; j <= n; ++j)
dp[i][j] = INF;
for(i = 1; i < n; ++i)
{
scanf("%d %d",&u, &v);
g[u][ num[u]++ ] = v;
flag[v] = 1;
}
for(i = 1; i <= n; ++i)
{
if(flag[i] == 0)
{
root = i;
break;
}
}
dfs(root);
int result = INF;
for(i = 1; i <= n; ++i)
result = min(result, dp[i][p]);
printf("%d\n", result);
}
return 0;
}