正文
增加 16 行删除 16 行
7 行未改动891011121314151617181920 行未改动404142434445464748495051525354555657585960614 行未改动66676869707172737416 行未改动91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312471 行未改动7 行未改动```void dfs(int from,int fa) {for(遍历与from相连的边) {if(to==fa) {continue;}dfs(to,from);使用 dp[to] 更新 dp[from];}}```讲解一道模板题,了解树形 DP 使用方法。20 行未改动using namespace std;const int N=6e3+10;struct edge{int to,next;}ee[N<<1];//两倍int head[N],ne;void ae(int from,int to) {//链式前向星ee[++ne]={to,head[from]};head[from]=ne;}int n,w[N],dp[N][2];void dfs(int from,int fa) {dp[from][1]=w[from];//设置初始状态for(int i=head[from];i;i=ee[i].next) {int to=ee[i].to;if(to==fa) continue;//防止重复访问dfs(to,from);//递归求解 dp[to]//更新dp[from][0]+=max(dp[to][0],dp[to][1]);dp[from][1]+=dp[to][0];}}4 行未改动cin>>x>>y;ae(y,x),ae(x,y);}dfs(1,0);//最后要在两个合法状态中取最大cout<<max(dp[1][0],dp[1][1]);return 0;}```16 行未改动```cppvoid dfs(int from,int fa) {for(遍历与from相连的边) {if(to==fa) {continue;}dfs(to,from);使用 dp[to] 更新 dp[from];}}void ddfs(int from,int fa) {for(遍历与from相连的边) {if(to==fa) {continue;}使用 dp[from] 更新 dp[to];dfs(to,from);}}/*还有另外一种写法,本质上都是通过已知的更新未知。void ddfs(int from,int fa) {if(from不是根) {使用 dp[fa] 更新 dp[from];}for(遍历与from相连的边) {if(to==fa) {continue;}dfs(to,from);}}*/```71 行未改动7 行未改动891011121314151617181920 行未改动404142434445464748495051525354555657585960614 行未改动66676869707172737416 行未改动91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312471 行未改动7 行未改动```void dfs(int from,int fa) {for(遍历与from相连的边) {if(to==fa) {continue;}dfs(to,from);使用 dp[to] 更新 dp[from];}}```讲解一道模板题,了解树形 DP 使用方法。20 行未改动using namespace std;const int N=6e3+10;struct edge{int to,next;}ee[N<<1];//两倍int head[N],ne;void ae(int from,int to) {//链式前向星ee[++ne]={to,head[from]};head[from]=ne;}int n,w[N],dp[N][2];void dfs(int from,int fa) {dp[from][1]=w[from];//设置初始状态for(int i=head[from];i;i=ee[i].next) {int to=ee[i].to;if(to==fa) continue;//防止重复访问dfs(to,from);//递归求解 dp[to]//更新dp[from][0]+=max(dp[to][0],dp[to][1]);dp[from][1]+=dp[to][0];}}4 行未改动cin>>x>>y;ae(y,x),ae(x,y);}dfs(1,0);//最后要在两个合法状态中取最大cout<<max(dp[1][0],dp[1][1]);return 0;}```16 行未改动```cppvoid dfs(int from,int fa) {for(遍历与from相连的边) {if(to==fa) {continue;}dfs(to,from);使用 dp[to] 更新 dp[from];}}void ddfs(int from,int fa) {for(遍历与from相连的边) {if(to==fa) {continue;}使用 dp[from] 更新 dp[to];dfs(to,from);}}/*还有另外一种写法,本质上都是通过已知的更新未知。void ddfs(int from,int fa) {if(from不是根) {使用 dp[fa] 更新 dp[from];}for(遍历与from相连的边) {if(to==fa) {continue;}dfs(to,from);}}*/```71 行未改动