标签:pre space efi names lin line ace clu add
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#define ll long long
using namespace std;
inline int read(){
int x=0,o=1;char ch=getchar();
while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
if(ch=='-')o=-1,ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
return x*o;
}
const int N=2e5+5;
int n,a[N];ll ans,cost[N],f[N];
int tot,head[N],nxt[N<<1],to[N<<1];
inline void add(int a,int b){
nxt[++tot]=head[a];head[a]=tot;to[tot]=b;
}
inline void pre_dfs(int u,int fa){
cost[u]=a[u];
for(int i=head[u];i;i=nxt[i]){
int v=to[i];if(v==fa)continue;
pre_dfs(v,u);cost[u]+=cost[v];
}
}
inline void dfs(int u,int fa){
for(int i=head[u];i;i=nxt[i]){
int v=to[i];if(v==fa)continue;
dfs(v,u);f[u]+=f[v]+cost[v];
}
}
inline void dp(int u,int fa){
for(int i=head[u];i;i=nxt[i]){
int v=to[i];if(v==fa)continue;
f[v]=f[u]-cost[v]+cost[1]-cost[v];
ans=max(ans,f[v]);dp(v,u);
}
}
int main(){
n=read();for(int i=1;i<=n;++i)a[i]=read();
for(int i=1;i<n;++i){
int a=read(),b=read();
add(a,b);add(b,a);
}
pre_dfs(1,0);dfs(1,0);ans=f[1];dp(1,0);
printf("%lld\n",ans);
return 0;
}
CF1092F Tree with Maximum Cost
标签:pre space efi names lin line ace clu add
原文地址:https://www.cnblogs.com/PPXppx/p/11845449.html