医院设置
题目链接:医院设置
题目描述
设有一棵二叉树(如右图)。其中,圈中的数字表示结点中居民的人口。圈边上数字表示结点编号,现在要求在某个结点上建立一个医院,使所有居民所走的路程之和为最小,同时约定,相邻接点之间的距离为1。如 右图中,若医院建在:
1处,则距离和=4+12+220+240=136
3处,则距离和=4*2+13+20+40=81
………….
输入格式
第一行一个整数n,表示树的结点数。(n<=100)
接下来的n行每行描述了一个结点的状况,包含三个整数,整数之间用空格(一个或多个)分隔,其中:第一个数为居民人口数;第二个数为左链接,为0表示无链接;第三个数为右链接。
输出格式
一个整数,表示最小距离和。
样例输入输出
输入
5
13 2 3
4 0 0
12 4 5
20 0 0
40 0 0
输出
81
解题思路
枚举每一个点到其他点的最短路,求出最小值就OK!
#include<iostream>
#include<cstdio>
using namespace std;
int n,c[110],sss=0x3f3f3f3f;
int a[110],b[110][110];
struct abcdefg{
int now,num;
}f[1000000];
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
int x,y;
scanf("%d%d",&x,&y);
b[i][x]=1;
b[x][i]=1;
b[i][y]=1;
b[y][i]=1;
}
for(int i=1;i<=n;i++)
{
int hd=0,tl=1;
memset(c,0x3f3f3f3f,sizeof(c));
f[1].now=i;
f[1].num=0;
c[i]=0;
while(hd<tl)
{
hd++;
for(int j=1;j<=n;j++)
{
if(f[hd].num+1<c[j]&&b[f[hd].now][j])
{
c[j]=f[hd].num+1;
tl++;
f[tl].now=j;
f[tl].num=c[j];
}
}
}
int ans=0;
for(int j=1;j<=n;j++)
{
ans+=c[j]*a[j];
}
if(ans<sss)
sss=ans;
}
cout<<sss;
}