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
Hint
[A subtree with nodes (1, 2, 3, 6, 7, 8) will become isolated if roads 1-4 and 1-5 are destroyed.]
又是一道思索了半天忍不住去看题解了的题目,自己还是太菜了啊……
这道题的状态设置的巧妙之处在于,刚开始将它们都看成一个单独的点,所以除了dp[i][1]=0之外,其他的值都为inf,这样在进行dfs时,对于每个遇到的子节点,相当于它与外界的连接多了一条,所以dp[i][1~p]均需要加一,代表以i为节点的子树要维持这个节点数要多断一条边,即这条新遇见的子树。接下来,就是我们熟悉的背包过程。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
#define maxn 160
#define inf 0x3f3f3f3f
using namespace std;
vector<int> g[maxn];
int dp[maxn][maxn];
int vis[maxn];
int n,p;
int ans;
void dfs(int u)
{
dp[u][1]=0;
for(int i=0; i<g[u].size(); i++)
{
int v=g[u][i];
dfs(v);
for(int j=p; j>=1; j--)
{
dp[u][j]+=1; //注意每次的加一必须在背包过程的这个循环里加,因为加一即代表断开与子树的连接,而接下来背包的过程是在与子树连接的情况下,所用到的dp[u][j]中的j一定是小于现在(下面用到的dp[u][j]是与这课子树相连的情况),所以从大到小的背包过程中赋值才是正确的。
for(int k=1; k<j; k++)
{
dp[u][j]=min(dp[u][j],dp[u][j-k]+dp[v][k]);
}
}
}
}
int main()
{
cin>>n>>p;
memset(dp,0x3f,sizeof(dp));
memset(vis,0,sizeof(vis));
for(int i=0; i<=n; i++)
g[i].clear();
for(int i=1; i<=n-1; i++)
{
int a,b;
scanf("%d%d",&a,&b);
g[a].push_back(b);
vis[b]=1;
}
int root;
for(int i=1;i<=n;i++)
if(!vis[i]){
root=i;
break;
}
dfs(root);
ans=dp[root][p];
for(int i=1;i<=n;i++)
ans=min(ans,dp[i][p]+1);
cout<<ans<<endl;
return 0;
}