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 cocould do. he wants to know the minimum number of roads whose destruction wowould 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.]
N and p are given. There are n nodes in total. The minimum number of edges is required. The remaining p nodes are required.
Idea: Typical tree-like DP,
Dp [s] [I]: records the s node and obtains the minimum number of edges removed from the subtree of a tree with j nodes.
Considering his son k
1) if k subtree is not removed
Dp [s] [I] = min (dp [s] [j] + dp [k] [I-j]) 0 <= j <= I
2) if k subtree is removed
Dp [s] [I] = dp [s] [I] + 1
Total is
Dp [s] [I] = min (dp [s] [j] + dp [k] [I-j]), dp [s] [I] + 1)
# Include <stdio. h> # include <string. h ># include <algorithm> using namespace std; int n, p, root; int dp [155] [155]; int father [155], son [155], brother [155]; void dfs (int root) {int I, j, k, tem; for (I = 0; I <= p; I ++) dp [root] [I] = 10000000; dp [root] [1] = 0; k = son [root]; while (k) {dfs (k ); for (I = p; I> = 1; I --) {tem = dp [root] [I] + 1; for (j = 1; j <I; j ++) tem = min (tem, dp [k] [I-j] + dp [root] [j]); dp [root] [I] = tem;} K = brother [k] ;}} int solve () {int ans, I; dfs (root); ans = dp [root] [p]; for (I = 1; I <= n; I ++) // except for the root node, if other nodes want to be independent of each other, they must first disconnect from the parent node, therefore, add 1 ans = min (ans, dp [I] [p] + 1); return ans;} int main () {int I, x, y; while (~ Scanf ("% d", & n, & p) {memset (father, 0, sizeof (father); memset (son, 0, sizeof (son); for (I = 1; I <n; I ++) {scanf ("% d", & x, & y ); father [y] = 1; // record the father's Day point brother [y] = son [x]; // record brother node son [x] = y; // record subnode} for (I = 1; I <= n; I ++) {if (! Father [I]) // find the root node {root = I; break ;}} printf ("% d \ n", solve () ;}return 0 ;}