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
#include <iostream> #include <cstdio> #include <cstring> using namespace std; #define maxn 180 #define inf 0x3f3f3f3f int first[maxn],nxt[maxn],vv[maxn]; int fa[maxn],e,n,p; int dp[maxn][maxn]; void addEdge(int u,int v) { vv[e] = v; nxt[e] = first[u]; first[u] = e++; fa[v] = u; } void dfs(int u) { for(int i = first[u];i != -1;i = nxt[i]) { int v = vv[i]; dfs(v); for(int j = p;j >= 0;j--) { int temp = dp[u][j] + 1; for(int k = 0;k <= j;k++) { temp = min(temp,dp[u][k] + dp[v][j-k]); } dp[u][j] = temp; } } } int main() { //freopen("in.txt","r",stdin); while(scanf("%d%d",&n,&p)==2) { e = 0; memset(first,-1,sizeof(first)); memset(fa,0,sizeof(fa)); memset(dp,0x3f,sizeof(dp)); for(int i = 1;i <= n;i++) dp[i][1] = 0; for(int i = 1;i < n;i++) { int u,v; scanf("%d%d",&u,&v); addEdge(u,v); } for(int i = 1;i <= n;i++) { if(!fa[i]) { dfs(i); break; } } int ans = inf,pos; for(int i = 1;i <= n;i++) { if(dp[i][p] < ans || (dp[i][p] == ans && fa[i]==0)) { pos = i; ans = dp[i][p]; } } printf("%d\n",fa[pos]?ans+1:ans); } return 0; }