版本比较
换根 & 树形
正文
增加 16 行删除 16 行
7 行未改动8910111212131415151617181920 行未改动404142434444454646474849505152525354555657555657585960614 行未改动6667686970707172737416 行未改动919293949595969798989910010110210310410410510610710710810911011111111211311411511611711811811912012012112212312471 行未改动7 行未改动```void dfs(int from,int fa) { for(遍历与from相连的边) { if(to==fa) { continue; continue; } dfs(to,from); 使用 dp[to] 更新 dp[from]; 使用 dp[to] 更新 dp[from]; }}```讲解一道模板题,了解树形 DP 使用方法。20 行未改动using namespace std;const int N=6e3+10;struct edge{ int to,next;}ee[N<<1];//两倍 }ee[N<<1];//两倍int head[N],ne;void ae(int from,int to) {//链式前向星 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];//设置初始状态 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] //更新 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; continue; } dfs(to,from); 使用 dp[to] 更新 dp[from]; 使用 dp[to] 更新 dp[from]; }}void ddfs(int from,int fa) { for(遍历与from相连的边) { if(to==fa) { continue; continue; } 使用 dp[from] 更新 dp[to]; dfs(to,from); dfs(to,from); }}/*还有另外一种写法,本质上都是通过已知的更新未知。 还有另外一种写法,本质上都是通过已知的更新未知。void ddfs(int from,int fa) { if(from不是根) { 使用 dp[fa] 更新 dp[from]; } for(遍历与from相连的边) { if(to==fa) { continue; continue; } dfs(to,from); dfs(to,from); }}*/```71 行未改动