AcWing 1220. 生命之树
原题链接
中等
作者:
最后五分钟
,
2024-04-01 21:52:09
,
所有人可见
,
阅读 4
#include<bits/stdc++.h>
#define int long long
#define x first
#define y second
#define de(x) cout<<#x<<" = "<<x<<" "
#define deg(x) cout<<#x<<" = "<<x<<endl
using namespace std;
const int N=1e5+10,M=2*N;
typedef pair<int,int> PII;
int e[M],ne[M],h[N],idx;
int w[N];
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
int f[N][2];
void dfs(int u,int fa)
{
f[u][1]=w[u];
f[u][0]=-1e9;
for(int i=h[u];~i;i=ne[i])
{
int j=e[i];
if(j==fa)continue;
dfs(j,u);
f[u][1]+=max(0ll,f[j][1]);
f[u][0]=max(f[u][0],max(f[j][1],f[j][0]));
}
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin>>n;
memset(h,-1,sizeof h);
for(int i=1;i<=n;i++)
{
cin>>w[i];
}
for(int i=1;i<=n-1;i++)
{
int a,b;
cin>>a>>b;
add(a,b);
add(b,a);
}
dfs(1,-1);
int res=max(f[1][0],f[1][1]);
cout<<res<<endl;
return 0;
}