Rqnoj 319 医院的设置 题解

      医院设置是一道经典的Floyed题目,经典到第一次听Floyed时老师就是讲的这道题。但是rq上把它划到搜索中,可能有搜索的解法吧,现在就不打了,以后有时间一定补上。

      下面切入正题。

 

【题目描述】(rqnoj319)
设有一棵二叉树,其中圈中的数字表示结点居民的人口,圈边上的数字表示结点的编号。现在要求在某个结点上建立一个医院,使所有居民所走的路径之和为最小,同时约定,相邻接点之间的距离为1,就本图而言,若医院建在1处,则距离和=4+12+2*20+2*40=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

      题目很简单,数据量也很小。100的数据n3的Floyed显然可以承受。把权值都赋为1,做一遍多源最短路,再将n个节点当做医院的情况逐个枚举,找到最小值即可。

 

      参考代码:

1 program hospital;
2 var
3 a:array[1..100]of longint;
4 tot,min:longint;
5 f:array[0..100,0..100]of integer;
6 i,j,k,n,x,y:integer;
7 begin
8 readln(n);
9 for i:=1 to n do
10 for j:=1 to n do
11 if i<>j then
12 f[i,j]:=maxint;
13 for i:=1 to n do
14 begin
15 readln(a[i],x,y);
16 f[i,y]:=1;
17 f[i,x]:=1;
18 f[x,i]:=1;
19 f[y,i]:=1;
20 end;
21 for k:=1 to n do //最短路。注意k一定在最外层,否则会出错
22 for i:=1 to n do
23 if(i<>k)then
24 for j:=1 to n do
25 if(i<>j)and(j<>k)then
26 if f[i,j]>f[i,k]+f[k,j] then f[i,j]:=f[i,k]+f[j,k];
27 min:=maxlongint;
28 for i:=1 to n do //枚举找最优解
29 begin
30 tot:=0;
31 for j:=1 to n do
32 if f[i,j]<>maxint then tot:=tot+a[j]*f[i,j];
33 if tot<min then min:=tot;
34 end;
35 writeln(min);
36 end.
 

 

(saltless原创,转载请注明出处)

posted on 2010-08-07 07:06  saltless  阅读(405)  评论(0编辑  收藏  举报

导航