2016-05-31 13:25:45
Topic Link: Rokua P1273 cable TV network
Main topic:
Take as many leaf nodes as possible on a given tree of weights, making sigma (val[selected leaf node])-sigma (cost[)) >=0
Solution:
Tree-like DP backpack DP
DP[I][J] represents the maximum profit obtained by selecting J leaf nodes for the subtree of the root of the I node.
Transfer equation
Dp[i][j]=max (Dp[i][j],dp[i][j-k]+dp[son][k]-cost[son][i]);
Places to be aware of
When writing the initial value, be aware that all but dp[i][0]=0 are-inf.
1 //Cable TV Network (Rokua no.1273)2 //tree-like DP backpack DP3#include <stdio.h>4#include <algorithm>5 using namespacestd;6 Const intmaxn=3010;7 intDP[MAXN][MAXN];8 structEdge9 {Ten intto ; One intCost ; A intNext; - Edge () {} -EdgeintTo,intCostintnext): To, cost, next (next) {} the }; - Edge N[MAXN]; - intHEAD[MAXN]; - intCNT; + voidInsertintXintYintz) - { +n[++cnt]=Edge (Y,z,head[x]); Ahead[x]=CNT; at return ; - } - intn,m; - intVAL[MAXN]; - intDasointx) - { in if(x>n-M) - { todp[x][1]=Val[x]; + return 1; - } the intsum=0; * for(intI=head[x];i;i=n[i].next) $ {Panax Notoginseng intSize=DFS (n[i].to); -sum+=size; the for(intj=sum;j>=0; j--) + { A for(intk=1; k<=size;k++) the { +Dp[x][j]=max (dp[x][j],dp[x][j-k]+dp[n[i].to][k]-n[i].cost); - } $ } $ } - returnsum; - } the intMain () - {Wuyiscanf"%d%d",&n,&M); the for(intI=0; i<maxn;i++) - { WuFill (dp[i],dp[i]+maxn,-1000000); - } About for(intI=1; i<=n;i++) dp[i][0]=0; $ for(intI=1; i<=n-m;i++) - { - intx; -scanf"%d",&x); A for(intj=1; j<=x;j++) + { the intTo,val; -scanf"%d%d",&to,&val); $ Insert (i,to,val); the } the } the for(inti=n-m+1; i<=n;i++) the { -scanf"%d",&val[i]); in } theDFS (1); the for(inti=m;i>=0; i--) About { the if(dp[1][i]>=0) the { theprintf"%d", i); + return 0; - } the }Bayi return 0; the}
Rokua P1273 Cable TV network