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);
}
复制代码

 

posted @   董晓  阅读(94)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示