标签:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 #include<cmath> 5 6 #define maxn 100001 7 8 using namespace std; 9 10 long long tot=0,w[maxn],f[maxn],ans; 11 12 inline int in() 13 { 14 int x=0;char ch=getchar(); 15 while(ch<‘0‘||ch>‘9‘)ch=getchar(); 16 while(ch<=‘9‘&&ch>=‘0‘)x=x*10+ch-‘0‘,ch=getchar(); 17 return x; 18 } 19 20 struct ed{ 21 int to,c,last; 22 }edge[maxn*2]; 23 24 int last[maxn],cnt=0,a[maxn]; 25 26 bool vis[maxn]; 27 28 void add(int u,int v,int c) 29 { 30 edge[++cnt].to=v,edge[cnt].c=c,edge[cnt].last=last[u],last[u]=cnt; 31 edge[++cnt].to=u,edge[cnt].c=c,edge[cnt].last=last[v],last[v]=cnt; 32 } 33 34 void DP(int pos) 35 { 36 w[pos]=a[pos];vis[pos]=1; 37 for(int i=last[pos];i;i=edge[i].last) 38 { 39 int u=edge[i].to; 40 if(vis[u])continue; 41 DP(u); 42 w[pos]+=w[u]; 43 f[pos]+=w[u]*edge[i].c+f[u]; 44 } 45 } 46 47 void dfs(int poi,long long val) 48 { 49 vis[poi]=1;ans=min(ans,val); 50 for(int i=last[poi];i;i=edge[i].last) 51 if(!vis[edge[i].to]) 52 dfs(edge[i].to,val+(tot-2*w[edge[i].to])*edge[i].c); 53 } 54 55 int main() 56 { 57 int n,u,v,c; 58 n=in(); 59 for(int i=1;i<=n;i++)a[i]=in(),tot+=a[i]; 60 for(int i=1;i<n;i++) 61 { 62 u=in();v=in();c=in(); 63 add(u,v,c); 64 } 65 DP(1);ans=f[1]; 66 memset(vis,0,sizeof(vis)); 67 dfs(1,f[1]); 68 printf("%lld",ans); 69 return 0; 70 }
【树形DP/搜索】BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会
标签:
原文地址:http://www.cnblogs.com/tuigou/p/4883410.html