H - Holiday's Accommodation ICPC 思维

连接:https://vjudge.net/contest/400668#problem/H

思路:对于每一条边,求 min(左边点的个数,右边点的个数)*边的权值*2

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1e5+10;
 4 typedef long long ll;
 5 ll ans;
 6 struct node
 7 {
 8     int v,w,nxt;
 9 }G[2*maxn];
10 int head[maxn];int num;
11 int siz[maxn];
12 int n;
13 void add(int u,int v,int w)
14 {
15     G[++num].v=v;G[num].w=w;G[num].nxt=head[u];head[u]=num;
16 }
17 void init()
18 {
19     memset(head,0,sizeof(head));
20     memset(siz,0,sizeof(siz));
21     num=0;
22     ans=0;
23 }
24 void dfs(int u,int fa)
25 {
26     siz[u]=1;
27     for(int i=head[u];i;i=G[i].nxt){
28         int v=G[i].v;
29         if(v==fa) continue;
30         dfs(v,u);
31         ans+=min(siz[v],n-siz[v])*2*G[i].w;
32         siz[u]+=siz[v];
33     }
34 }
35 int main()
36 {
37     int T;
38     scanf("%d",&T);
39     int Case=0;
40     while(T--){
41         init();
42         scanf("%d",&n);
43         for(int i=1;i<n;i++){
44             int u,v,w;
45             scanf("%d%d%d",&u,&v,&w);
46             add(u,v,w);
47             add(v,u,w);
48         }
49         dfs(1,0);
50         printf("Case #%d: %lld\n",++Case,ans);
51     }
52     return 0;
53 }
View Code

 

posted @ 2020-10-12 09:47  古比  阅读(96)  评论(0编辑  收藏  举报