2577 医院设置
时间限制: 1 s
空间限制: 32000 KB
题目等级 : 黄金 Gold
题目描述 Description
设有一棵二叉树,如下图
其中,圈中数字表示结点居民的人口.圈边上数字表示结点编号,.现在要求在某个结点上建立一个医院,使所有居民所走的路程之和为最小,同时约定,相邻结点之间 的距离为1.如上图中,若医院建在:
1处:则距离之和=4+12+2*20+2*40=136
3处:则距离之和=4*2+13+20+40=81
…….
输入描述 Input Description
第一行一个整数n,表示树的结点数。(n<=100)
接下来的n行每行描述了一个结点的状况,包含三个整数,整数之间用空格(一个或多个)分隔,其中:第一个数为居民人口数;第二个数为左链接,为0表示表链接;第三个数为右链接。
输出描述 Output Description
一个整数,表示最小距离和。
样例输入 Sample Input
5
13 2 3
4 0 0
12 4 5
20 0 0
40 0 0
样例输出 Sample Output
81
数据范围及提示 Data Size & Hint
无
分类标签 Tags 点此展开
Flyoed + 暴力
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 const int MAXN=10001; 6 const int maxn=0x7fffffff; 7 int map[MAXN][MAXN]; 8 int f[MAXN]; 9 int w[MAXN]; 10 int main() 11 { 12 int n; 13 scanf("%d",&n); 14 for(int i=1;i<=n;i++) 15 for(int j=1;j<=n;j++) 16 map[i][j]=maxn; 17 for(int i=1;i<=n;i++) 18 { 19 int p,x,y; 20 scanf("%d%d%d",&p,&x,&y); 21 w[i]=p; 22 if(x!=0) 23 map[i][x]=map[x][i]=1; 24 if(y!=0) 25 map[i][y]=map[y][i]=1; 26 } 27 for(int k=1;k<=n;k++) 28 { 29 for(int i=1;i<=n;i++) 30 { 31 for(int j=1;j<=n;j++) 32 { 33 if(map[i][k]!=maxn&&map[k][j]!=maxn) 34 { 35 if(map[i][j]>map[i][k]+map[k][j]) 36 { 37 map[i][j]=map[i][k]+map[k][j]; 38 } 39 } 40 } 41 } 42 } 43 int ans=maxn; 44 for(int i=1;i<=n;i++) 45 { 46 int now=0; 47 for(int j=1;j<=n;j++) 48 { 49 if(j!=i) 50 now=now+map[j][i]*w[j]; 51 } 52 if(now<ans) 53 ans=now; 54 } 55 printf("%d",ans); 56 return 0; 57 }