思路:dp[i][0]就表示以i节点为根节点,不选i节点的最大值,dp[i][1]表示以i节点为根节点,选择i节点的最大值,我们建好图,然后v为u的子节点,当u节点不选的时候,那么后面v节点选和不选我们找一个最大值dp[u][0]+=max(dp[v][0],dp[v][1])。当u节点选的时候那么v节点肯定不能选,dp[u][1]+=dp[v][0],题目说了是一棵益校长为根的树,那么我们找到校长(根),最后答案就是max(dp[root][1],dp[root][0)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=998244353;
const int N=2e6+10;
const int M=2e3+10;
const int inf=0x7f7f7f7f;
const int maxx=2e5+7;
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return a*(b/gcd(a,b));
}
template <class T>
void read(T &x)
{
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-')
op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op)
x = -x;
}
template <class T>
void write(T x)
{
if(x < 0)
x = -x, putchar('-');
if(x >= 10)
write(x / 10);
putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
ll res=1%p;
while(b)
{
if(b&1) res=res*a%p;
a=1ll*a*a%p;
b>>=1;
}
return res;
}
vector<int> G[6005];
int dp[6005][2];
int a[6005];
int vis[6005];
void dfs(int u)
{
dp[u][1]=a[u];
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
//if(v==fa)continue;
dfs(v);
dp[u][1]+=dp[v][0];
dp[u][0]+=max(dp[v][1],dp[v][0]);
}
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int i=0;i<n-1;i++)
{
int u,v;
cin>>u>>v;
G[v].push_back(u);
vis[u]++;
// G[v].push_back(u);
}
int u,v;cin>>u>>v;
int root=1;
while(vis[root])root++;
dfs(root);
int ans=max(dp[root][0],dp[root][1]);
cout<<ans<<endl;
return 0;
}

京公网安备 11010502036488号