E85 换根DP P2986 [USACO10MAR] Great Cow Gathering G
视频链接:E85 换根DP P2986 [USACO10MAR] Great Cow Gathering G_哔哩哔哩_bilibili


P2986 [USACO10MAR] Great Cow Gathering G - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
// 换根DP O(n) #include <iostream> #include <cstring> #include <algorithm> #include <vector> using namespace std; int read(){ int s=1,d=0;char c=getchar(); for(;!isdigit(c);c=getchar()) if(c=='-') s=-1; for(;isdigit(c);c=getchar()) d=10*d+c-'0'; return s*d; } #define LL long long const int N=100005; int n; struct E{int v,w;}; vector<E> e[N<<1]; LL c[N],sz[N],f[N],cnt,ans=1e18; void dfs(int u,int fa){ sz[u]=c[u]; for(auto i:e[u]){ int v=i.v,w=i.w; if(v==fa) continue; dfs(v,u); sz[u]+=sz[v]; f[u]+=f[v]+sz[v]*w; } } void dfs2(int u,int fa){ for(auto i:e[u]){ int v=i.v,w=i.w; if(v==fa) continue; f[v]=f[u]-sz[v]*w+(cnt-sz[v])*w; ans=min(ans,f[v]); dfs2(v,u); } } int main(){ n=read(); for(int i=1;i<=n;i++){ c[i]=read(); cnt+=c[i]; } for(int j=1,u,v,w;j<n;j++){ u=read();v=read();w=read(); e[u].push_back({v,w}); e[v].push_back({u,w}); } dfs(1,0); dfs2(1,0); printf("%lld\n",ans); }
浙公网安备 33010602011771号