Link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1520
Question: Give a workplace relationship diagram. Each person has his own value and each person has only one leader. The person I want to invite cannot be a person or his immediate leader, ask the maximum number of people who can be invited.
Idea: the entry question is that it is interesting to apply simple DP to a data structure like a tree. It is suggested that forest DP is more appropriate than forest DP. The first step is to build a tree. The root node is a node without Father's Day. For a node u on the tree, DP [u] [0] represents the maximum value that can be obtained without selecting this node, DP [u] [1] indicates the maximum value that can be obtained by selecting this node.
State transition equation: DP [u] [0] = sum (max (DP [v] [0], DP [v] [1]). If the current node is not selected, each of its subnodes can be selected or not selected.
DP [u] [1] = sum (DP [v] [0]). If you select the current node, each of its subnodes cannot be selected.
Code:
#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<map>#include<queue>#include<stack>#include<vector>#include<ctype.h>#include<algorithm>#include<string>#define PI acos(-1.0)#define maxn 6005#define INF 0x7ffffffftypedef long long LL;using namespace std;int score[maxn],head[maxn],top,dp[maxn][2];bool from[maxn];void init(){ memset(head,-1,sizeof(head)); memset(from,0,sizeof(from)); memset(dp,0,sizeof(dp)); top=0;}struct Edge{ int v; int next;} edge[maxn];int add_edge(int u,int v){ edge[top].v=v; edge[top].next=head[u]; head[u]=top++;}void dfs(int u){ for(int i=head[u]; i!=-1; i=edge[i].next) { int v=edge[i].v; dfs(v); dp[u][1]+=dp[v][0]; dp[u][0]+=max(dp[v][1],dp[v][0]); } dp[u][1]+=score[u];}int main(){ int tot,u,v; while(~scanf("%d",&tot)) { init(); for(int i=1; i<=tot; i++) scanf("%d",&score[i]); while(scanf("%d%d",&u,&v)) { if(u==0&&v==0) break; add_edge(v,u); from[u]=true; } for(int i=1; i<=tot; i++) { if(!from[i]) dfs(i); } int ans=0; for(int i=1; i<=tot; i++) { if(from[i]==0) ans+=max(dp[i][0],dp[i][1]); } printf("%d\n",ans); } return 0;}
HDU 1520 anniversary party tree DP