题目描述
设有一棵二叉树,如图:
其中,圈中的数字表示结点中居民的人口。圈边上数字表示结点编号,现在要求在某个结点上建立一个医院,使所有居民所走的路程之和为最小,同时约定,相邻接点之间的距离为 11。如上图中,若医院建在1 处,则距离和 =4+12+2\times20+2\times40=136=4+12+2×20+2×40=136;若医院建在 33 处,则距离和 =4\times2+13+20+40=81=4×2+13+20+40=81。
输入格式
第一行一个整数 nn,表示树的结点数。
接下来的 nn 行每行描述了一个结点的状况,包含三个整数 w, u, vw,u,v,其中 ww 为居民人口数,uu 为左链接(为 00 表示无链接),vv 为右链接(为 00 表示无链接)。
输出格式
一个整数,表示最小距离和。
输入输出样例
输入 #1复制
5 13 2 3 4 0 0 12 4 5 20 0 0 40 0 0
输出 #1复制
81
说明/提示
数据规模与约定
对于 100\%100% 的数据,保证 1 \leq n \leq 1001≤n≤100,0 \leq u, v \leq n0≤u,v≤n,1 \leq w \leq 10^51≤w≤105。
题解:
树的重心模板题。注意dp转移时:
/*keep on going and never give up*/
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define fast std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
inline int read()
{
int x=0,k=1; char c=getchar();
while(c<'0'||c>'9'){if(c=='-')k=-1;c=getchar();}
while(c>='0'&&c<='9')x=(x<<3)+(x<<1)+(c^48),c=getchar();
return x*k;
}
const int maxn=3e5+10;
const int mod=998244353;
int n,m,k,ans=1e12,f[maxn],size[maxn],w[maxn];
struct node{
int to,next;
}e[maxn];int head[maxn],tot;
void add(int x,int y){ e[++tot].to=y;e[tot].next=head[x];head[x]=tot;}
void dfs(int u, int fa, int dep){
size[u] = w[u];
for(int i = head[u]; i; i = e[i].next){
if(e[i].to != fa)
dfs(e[i].to, u, dep + 1), size[u] += size[e[i].to];
}
f[1] += w[u] * dep;
}
void dp(int u,int fa){
for(int i=head[u];i;i=e[i].next)
if(e[i].to!= fa)
f[e[i].to]=f[u]+size[1]-size[e[i].to]*2,dp(e[i].to,u);
ans = min(ans,f[u]);
}
signed main(){
n=read();for(int i=1;i<=n;i++){
int w1=read(),x1=read(),y1=read();
w[i]=w1;
if(x1)add(i,x1),add(x1,i);
if(y1)add(i,y1),add(y1,i);
}
dfs(1,0,0);
dp(1,0);
cout<<ans;
}