【Luogu】P3574FAR_FarmCraft(树形贪心)
想了一个错的贪心爆零了,气死。
#include<cstdio> #include<cctype> #include<cstring> #include<algorithm> #include<cstring> #define maxn 500050 using namespace std; inline long long read(){ long long num=0,f=1; char ch=getchar(); while(!isdigit(ch)){ if(ch=='-') f=-1; ch=getchar(); } while(isdigit(ch)){ num=num*10+ch-'0'; ch=getchar(); } return num*f; } struct Edge{ int next,to; }edge[maxn*2]; int head[maxn],num; inline void add(int from,int to){ edge[++num]=(Edge){head[from],to}; head[from]=num; } long long q[maxn]; long long f[maxn]; long long s[maxn]; int sta[maxn],top; bool cmp(int a,int b){ return f[a]>f[b]; } void dfs(int x,int fa){ int ret=top; for(int i=head[x];i;i=edge[i].next){ int to=edge[i].to; if(to==fa) continue; dfs(to,x); s[x]+=2+s[to]; sta[++top]=to; } if(x^1) f[x]=q[x]-s[x]; int now=s[x]; sort(sta+ret+1,sta+top+1,cmp); for(int i=ret+1;i<=top;++i){ int to=sta[i]; now-=s[to]+2; f[x]=max(f[x],f[to]-now-1); } f[x]=max(f[x],0LL); top=ret; } int main(){ int n=read(); for(int i=1;i<=n;++i) q[i]=read(); for(int i=1;i<n;++i){ int from=read(),to=read(); add(from,to); add(to,from); } dfs(1,1); printf("%lld\n",max(f[1],q[1])+n*2-2); return 0; }