codevs 2577 医院设置

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

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 using namespace std;
 5 const int maxn=0x7f;
 6 int ans=0x7fffffff,people[1001],map[1001][1001],l,r;
 7 int main()
 8 {
 9     int n,now=1,ans_now=0;
10     memset(map,1,sizeof(map));
11     cin>>n;
12     for(int i=1;i<=n;++i)
13     {
14         cin>>people[i]>>l>>r;
15         if(l!=0)
16         map[l][i]=map[i][l]=1;
17         if(r!=0)
18         map[r][i]=map[i][r]=1;
19     }
20     for(int k=1;k<=n;++k)
21     for(int i=1;i<=n;++i)
22     for(int j=1;j<=n;++j)
23     if(map[i][j]>map[i][k]+map[k][j])
24     map[i][j]=map[i][k]+map[k][j];
25     for(int now=1;now<=n;now++)
26     {
27         ans_now=0;
28         for(int i=1;i<=n;++i)
29         {
30             if(i!=now)
31             ans_now+=people[i]*map[now][i];
32         }
33         ans=min(ans,ans_now);
34     } 
35     cout<<ans<<endl;
36     return 0;
37 }
原文地址:https://www.cnblogs.com/sssy/p/6725011.html