The tree backpack as a group backpack, the return of the temporary negative is also possible, and the value of the income is also very large, so no longer let the income of the current subscript, put into the array to save, set F[x][t] for the X-root of the sub-tree select T to watch the program, The biggest benefit of the TV station (let you ask what is not necessarily exist in the array inside, it may be set to subscript and then judge the feasibility)
This problem is very special, the general packet backpack is not so big data, but because the actual effective leaf node is very few, so can be optimized (see note)
Also note the setting of the initial value of the F array
#include <algorithm> #include <iostream> #include <cstring> #include <cstdio>using namespace STD; #define DEBUG (x) cerr << #x << "=" << x << endl;const int maxn = + 10;const int INF = (1& LT;<30)/3; Here is a very pit ... First written 1<<30/3 operation 30/3, the result has become-8 ... int n,m,f[maxn][maxn],last[maxn],ans,edge_tot,vis[maxn],son[maxn];struct edge{int u,v,w,to; Edge () {} edge (int u, int v, int w, int to): U (U), V (v), W (W), to (to) {}}E[MAXN * 2];inline void Add (int u, int v, int w ) {E[++edge_tot] = Edge (U, V, W, Last[u]); Last[u] = Edge_tot;} void Dfs (int x) {vis[x] = 1; if (n-m+1 <= x && x <= N) {son[x] = 1;//here ... Note that not son[x] traditional subtree size, but how many user nodes are included} for (int i=last[x]; i; i=e[i].to) {int v = e[i].v, w = E[I].W; if (Vis[v]) continue; DFS (v); SON[X] + = Son[v]; for (int t=son[x]; t>=0; t--) {//Because son[x] is relatively small, so here the optimization is really very large for (int j=0; j<=son[v]; J + +) {F[x] [T] = max (f[x][t], f[x][t-j] + f[v][j]-W);//If there are 0 sub-trees, then there is no need to spend this w, so choose 0 will not affect}}}}int main () {SC ANF ("%d%d", &n, &m); for (int i=1; i<=n-m; i++) {int k,a,c; scanf ("%d", &k); for (int j=1; j<=k; J + +) {scanf ("%d%d", &a, &c); Add (i, A, c); Add (A, I, c); }} for (int i=1, i<=n; i++) {for (int j=1; j<=m; J + +) {F[i][j] =-inf; }//f[i][0] = 0; This is not set to 0 is OK, in the above transfer if there is a selection of 0 sub-tree appears will not affect the existing optimal yield} for (int i=n-m+1; i<=n; i++) {scanf ("%d", &f[i][1]); } dfs (1); for (int i=0; i<=m; i++) {if (F[1][i] >= 0) {ans = max (ans, i); }} printf ("%d\n", ans); return 0;}
P1273 Cable TV network-tree backpack