Topic Description:
Qaq ... Topic Analysis:
The dependency of the knapsack problem is called the tree-dependent backpack ...
The method of tree-type dynamic regression is used to solve
Transfer equation is not difficult
DP[I][J] represents the maximum value that can be achieved by the size of a tree backpack with the I root as J
In the actual operation we can use a virtual root to link the point without dependency ...
This transfer is nm2 N m 2 nm^2.
I heard that black technology can do nm N m nm
for (int i=w[now];i<=m;i++) Dp[now][i]=val[now];
for (int i=head[now];i;i=net[i])
{
dfs (to[i]);
for (int j=m-w[now];j>=0;j--) for
(int k=0;k<=j;k++)
Dp[now][j+w[now]]=std::max (DP[NOW][J+W[NOW]],DP [Now] [J+w[now]-k]+dp[to[i]][k]);
}
To pay attention to a problem, when the dependence on the formation of the ring, we can only select all the points within the ring, or all do not choose, so we need to use Tarjan first to shrink the point ... Topic Link:
Bzoj 2427
Luogu 2515
COGS 444 Ac Code:
#include <cstdio> #include <algorithm> #include <cstring> #include <iostream> const int maxm=
1001;
int DP[MAXM][501],D[MAXM];
int dfn[maxm],low[maxm],vis[maxm],c[maxm],stk[maxm],num,col,top;
int W[MAXM],VAL[MAXM],VAL[MAXM],W[MAXM],FA[MAXM];
int _head[maxm],_to[maxm<<1],_net[maxm<<1],_cnt;
int head[maxm],to[maxm<<1],net[maxm<<1],cnt;
int n,m;
inline void Addedge (int u,int v) {cnt++;
to[cnt]=v,net[cnt]=head[u],head[u]=cnt;
} inline void _addedge (int u,int v) {_cnt++;
_to[_cnt]=v,_net[_cnt]=_head[u],_head[u]=_cnt;
} void Tarjan (int x) {dfn[x]=low[x]=++num;
Stk[++top]=x;
Vis[x]=1;
for (int i=_head[x];i;i=_net[i]) {int p=_to[i];
if (!dfn[p]) {Tarjan (P);
Low[x]=std::min (Low[x],low[p]);
else if (Vis[p]) low[x]=std::min (low[x],dfn[p]);
} if (Low[x]==dfn[x]) {col++; while (stk[top]!=x) {C[stk[top]]=col;
vis[stk[top--]]=0;
} c[x]=col,vis[x]=0;
top--;
} void Dfs (int now) {for (int i=w[now];i<=m;i++) Dp[now][i]=val[now];
for (int i=head[now];i;i=net[i]) {DFS (to[i]); for (int j=m-w[now];j>=0;j--) for (int k=0;k<=j;k++) Dp[now][j+w[now]]=std::max (Dp[now][j+w[now)],
Dp[now][j+w[now]-k]+dp[to[i]][k]);
int main () {//freopen ("install.in", "R", stdin);
Freopen ("Install.out", "w", stdout);
scanf ("%d%d", &n,&m);
for (int i=1;i<=n;i++) scanf ("%d", &w[i]);
for (int i=1;i<=n;i++) scanf ("%d", &val[i]);
for (int i=1,x;i<=n;i++) {scanf ("%d", &fa[i]);
if (Fa[i]) _addedge (fa[i],i);
for (int i=1;i<=n;i++) if (!dfn[i]) Tarjan (i);
for (int i=1;i<=n;i++) {if (C[i]!=c[fa[i]]) Addedge (C[fa[i]],c[i]), d[c[i]]++;
W[c[i]]+=w[i];
Val[c[i]]+=val[i]; for (int i=1;i<=col;i++) IF (!d[i]) Addedge (0,i);
DFS (0);
printf ("%d\n", Dp[0][m]);
return 0; }