The key to a tree DP is how to handle recursive return information. This question Dp[i][0] indicates that the current maximum weight is not selected when I point. DP[I][1] Indicates the current maximum weight when I point is selected. State transition equation: Dp[u][[0]+=max (dp[v][0],dp[v][1]), dp[u][1]+=dp[v][0];
The code is as follows:
#include <iostream> #include <string.h> #include <math.h> #include <queue> #include < algorithm> #include <stdlib.h> #include <map> #include <set> #include <stdio.h>using namespace std; #define LL __int64#define Pi ACOs ( -1.0) const int Mod=100000000;const int Inf=0x3f3f3f3f;const double eqs=1e -8;int dp[7000][2], c[7000], Vis[7000];int head[7000], cnt, n;struct node{int u, V, next;} edge[100000];void Add (int u, int v) {edge[cnt].v=v; Edge[cnt].next=head[u]; head[u]=cnt++;} void Dfs (int u) {vis[u]=1; Dp[u][1]=c[u]; for (int i=head[u];i+1;i=edge[i].next) {int v=edge[i].v; if (!vis[v]) {DFS (v); Dp[u][0]+=max (dp[v][0],dp[v][1]); DP[U][1]+=DP[V][0]; }}}void init () {memset (vis,0,sizeof (VIS)); memset (head,-1,sizeof (head)); cnt=0; Memset (Dp,0,sizeof (DP));} int main () {int I, J, u, V; while (scanf ("%d", &n)!=eof) {for (i=1;i<=n;i++) {scanf ("%d", &c[i]); } init (); while (scanf ("%d%d", &u,&v)!=eof&&u&&v) {Add (u,v); Add (V,u); } dfs (1); printf ("%d\n", Max (dp[1][0],dp[1][1])); } return 0;}
HDU 1520 Anniversary Party (tree-shaped DP)