1、B站視頻鏈接:E17 樹形DP Luogu P1352 沒有上司的舞會_嗶哩嗶哩_bilibili
題目鏈接:沒有上司的舞會 - 洛谷
#include <bits/stdc++.h>
using namespace std;
const int N=6010;
int n;
int w[N];
vector<int>a[N];//鄰接表
bool fa[N];
int f[N][2];void dfs(int u){f[u][1]=w[u];//選根節點的快樂指數先加上for(int v:a[u]){//遍歷u的子節點,選或者不選 dfs(v);//深搜到底,再返回 f[u][0]+=max(f[v][0],f[v][1]);f[u][1]+=f[v][0];}
}
int main(){cin>>n;for(int i=1;i<=n;i++)cin>>w[i];for(int i=0;i<n-1;i++){//對應數組下標 int x,y;cin>>x>>y;//x是y的直接上司a[y].push_back(x);fa[x]=true; //x有父節點 }int root=1;while(fa[root])root++;//找到根節點dfs(root);cout<<max(f[root][0],f[root][1]);return 0;
}
?
?