bzoj1827 [Usaco2010 Mar]gather 奶牛大集会

题目链接

类似于找重心的写法,往牛多的那一头走(更优),直到找不到更优的

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<string>
 7 #include<cmath>
 8 #include<ctime>
 9 #include<queue>
10 #include<stack>
11 #include<map>
12 #include<set>
13 #define rre(i,r,l) for(int i=(r);i>=(l);i--)
14 #define re(i,l,r) for(int i=(l);i<=(r);i++)
15 #define Clear(a,b) memset(a,b,sizeof(a))
16 #define inout(x) printf("%d",(x))
17 #define douin(x) scanf("%lf",&x)
18 #define strin(x) scanf("%s",(x))
19 #define LLin(x) scanf("%lld",&x)
20 #define op operator
21 #define CSC main
22 typedef unsigned long long ULL;
23 typedef const int cint;
24 typedef long long LL;
25 using namespace std;
26 void inin(int &ret)
27 {
28     ret=0;int f=0;char ch=getchar();
29     while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();}
30     while(ch>='0'&&ch<='9')ret*=10,ret+=ch-'0',ch=getchar();
31     ret=f?-ret:ret;
32 }
33 int head[100010],next[200020],zhi[200020],ed;
34 LL c[100010],s[100010],dis[100010],w[200020];
35 LL sum;
36 void add(int a,int b,LL cc)
37 {
38     next[++ed]=head[a],head[a]=ed,zhi[ed]=b,w[ed]=cc;
39     next[++ed]=head[b],head[b]=ed,zhi[ed]=a,w[ed]=cc;
40 }
41 int n;
42 LL ans;
43 void dfs(int x,int fa)
44 {
45     ans+=c[x]*dis[x];
46     s[x]=c[x];
47     for(int i=head[x];i;i=next[i])if(zhi[i]!=fa)
48         dis[zhi[i]]=dis[x]+w[i],dfs(zhi[i],x),s[x]+=s[zhi[i]];
49 }
50 void getroot(int x,int fa)
51 {
52     for(int i=head[x];i;i=next[i])if(zhi[i]!=fa)
53         if((s[zhi[i]]<<1)>sum){ans-=(LL)((s[zhi[i]]<<1)-sum)*w[i],getroot(zhi[i],x);break;}
54 }
55 int main()
56 {
57     inin(n);
58     re(i,1,n)LLin(c[i]),sum+=c[i];
59     re(i,2,n)
60     {
61         int a,b,cc;
62         inin(a),inin(b),inin(cc);
63         add(a,b,cc);
64     }
65     dfs(1,0);
66     getroot(1,0);
67     printf("%lld",ans);
68      return 0;
69 }
原文地址:https://www.cnblogs.com/HugeGun/p/5236302.html