The first tree-like DP. This question is both dp and dfs and backpack. Dp [I] [j] indicates that the current access node number is I AND ITS subnodes are accessed for j times. Dp [I] [j] = max (dp [I] [j], dp [I] [j-r] + dp [t] [r]). T is a subnode of I. Read the code in detail.
[Cpp]
# Include <iostream>
# Include <vector>
Using namespace std;
Vector <int> tree [201];
Int dp [201] [201];
// Int val [201];
Int visited [201];
Int n, m;
Int max (int a, int B)
{
If (a> B)
Return;
Else return B;
}
Int main ()
{
Int I, father, v;
Void dfs (int k );
While (cin> n> m)
{
If (n + m = 0)
Break;
For (I = 0; I <= n; I ++)
Tree [I]. clear ();
Memset (dp,-1, sizeof (dp ));
Memset (visited, 0, sizeof (visited ));
For (I = 1; I <= n; I ++)
{
Cin> father> v;
Tree [father]. push_back (I );
/* Val [I] = v ;*/
Dp [I] [1] = v;
}
For (I = 0; I <= n; I ++)
Dp [I] [0] = 0;
Dp [0] [1] = 0;
M = m + 1;
Dfs (0 );
Cout <dp [0] [m] <endl;
}
Return 0;
}
Void dfs (int k)
{
Int t, j, r, I;
Visited [k] = 1;
For (I = 0; I <tree [k]. size (); I ++)
{
T = tree [k] [I];
If (visited [t] = 0)
Dfs (t );
For (j = m; j> = 1; j --)
For (r = 1; r <j; r ++)
{
If (dp [k] [j-r]! =-1 & dp [t] [r]! =-1)
Dp [k] [j] = max (dp [k] [j], dp [k] [j-r] + dp [t] [r]);
}
}
}
# Include <iostream>
# Include <vector>
Using namespace std;
Vector <int> tree [201];
Int dp [201] [201];
// Int val [201];
Int visited [201];
Int n, m;
Int max (int a, int B)
{
If (a> B)
Return;
Else return B;
}
Int main ()
{
Int I, father, v;
Void dfs (int k );
While (cin> n> m)
{
If (n + m = 0)
Break;
For (I = 0; I <= n; I ++)
Tree [I]. clear ();
Memset (dp,-1, sizeof (dp ));
Memset (visited, 0, sizeof (visited ));
For (I = 1; I <= n; I ++)
{
Cin> father> v;
Tree [father]. push_back (I );
/* Val [I] = v ;*/
Dp [I] [1] = v;
}
For (I = 0; I <= n; I ++)
Dp [I] [0] = 0;
Dp [0] [1] = 0;
M = m + 1;
Dfs (0 );
Cout <dp [0] [m] <endl;
}
Return 0;
}
Void dfs (int k)
{
Int t, j, r, I;
Visited [k] = 1;
For (I = 0; I <tree [k]. size (); I ++)
{
T = tree [k] [I];
If (visited [t] = 0)
Dfs (t );
For (j = m; j> = 1; j --)
For (r = 1; r <j; r ++)
{
If (dp [k] [j-r]! =-1 & dp [t] [r]! =-1)
Dp [k] [j] = max (dp [k] [j], dp [k] [j-r] + dp [t] [r]);
}
}
}