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.]
Source
正解:树形DP
解题报告:
感觉自己DP很萎,最近练一下DP。
f[i][j]记录以i为根结点的子树切出j个节点的最小代价,转移的话也很简单,f[x][j] = min{f[x][j],f[son[x][i]][k]+f[x][j-k]-2},减2是因为要减去算了两次的x到son[x][i]的那条边。
递归转移就可以了。
题解传送门:http://www.cnblogs.com/celia01/archive/2012/08/02/2619063.html
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
using namespace std;
const int MAXN = ;
int f[MAXN][MAXN];//f[i][j]记录以i为根结点的子树切出j个节点的最小代价
int du[MAXN];
vector<int>w[MAXN];
int n,p;
int ans;
int root; inline int getint(){
char c=getchar(); int w=,q=;
while(c!='-' && ( c<'' || c>'')) c=getchar();
if(c=='-') c=getchar(),q=;
while(c>='' && c<='') w=w*+c-'',c=getchar();
return q?-w:w;
} inline void dfs(int x){
if(x==root) f[x][]=w[x].size();
else f[x][]=w[x].size()+;//父边 for(int i=;i<w[x].size();i++) dfs(w[x][i]); for(int i=;i<w[x].size();i++)
for(int j=p;j>=;j--)
for(int k=;k<=j;k++) {
if(f[x][k]!=MAXN && f[w[x][i]][j-k]) {
f[x][j]=min(f[x][j],f[x][k]+f[w[x][i]][j-k]-);
}
}
} int main()
{
n=getint(); p=getint(); int x,y;
for(int i=;i<n;i++) {
x=getint(); y=getint();
w[x].push_back(y); du[y]++;
} for(int i=;i<=n;i++) for(int j=;j<=n;j++) f[i][j]=MAXN; for(int i=;i<=n;i++) if(du[i]==) { root=i; dfs(i); break; } ans=MAXN;
for(int i=;i<=n;i++) ans=min(ans,f[i][p]); printf("%d",ans); return ;
}