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.
* 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.
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.
11 6 1 2 1 3 1 4 1 5 2 6 2 7 2 8 4 9 4 10 4 11
2
题大意是:给你一棵节点为n的树,问至少砍几刀可以孤立出一棵节点为m的子树。
设d[i][j]为以i为根节点孤立出节点为j的子树至少需要砍得次数(注意:这个子树是包括根节点i的)。
接下来再说说怎么得到状态转移方程:
(1)当j为1的话,d[i][1]=节点i孩子的个数;
(2)若以i的孩子son[i]为根的子树不在以i为根节点孤立出节点数为j的子树的内部,则有没有以son[i]为根的子树无所谓;若以son[i]为根节点的子树有k个节点在以i为根孤立出节点数为j的子树中则 整个树分成两部分,此时,d[i][j]=d[i][j-k]+d[son[i]][k]-1;之所以减一是因为两个分开的子树重组在一起需要减去是他们分开的那一刀;总之我是这样想的也不知对也不对....
所以总的来说:d[i][j+k]=min{d[i][j]+d[son[i]][k]-1,d[i][j+k]};
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
vector<int>sons[155];
int dp[155][155];
int father[155];
int n,p;
int dfs(int root){
int i,j,k;
for(i=0;i<sons[root].size();i++)
dfs(sons[root][i]);
dp[root][1]=sons[root].size();
for(i=0;i<sons[root].size();i++){
for(j=p-1;j>0;j--){
if(dp[root][j]!=999999){
for(k=1;k<=p-j;k++){
if(dp[sons[root][i]][k]!=999999)
dp[root][j+k]=min(dp[root][j]+dp[sons[root][i]][k]-1,dp[root][j+k]);
}
}
}
}
return dp[root][p];
}
int main(){
int i,j,k;
int a,b;
int Min;
int root;
while(~scanf("%d %d",&n,&p)){
memset(father,0,sizeof(father));
for(i=1;i<=n;i++){
for(j=1;j<=p;j++){
dp[i][j]=999999;
}
}
for(i=0;i<n-1;i++){
scanf("%d %d",&a,&b);
sons[a].push_back(b);
father[b]=a;
}
root=1;
while(father[root]!=0)
root=father[root];
Min=dfs(root);
for(i=1;i<=n;i++)
if(Min>dp[i][p]+1)
Min=dp[i][p]+1;
printf("%d\n",Min);
}
return 0;
}