医院设置

来源:互联网 发布:淘宝运费模板怎么改 编辑:程序博客网 时间:2024/06/08 15:40

Description

  设有一棵二叉树(如右图)。其中,圈中的数字表示结点中居民的人口。圈边上数字表示结点编号,现在要求在某个结点上建立一个医院,使所有居民所走的路程之和为最小,同时约定,相邻接点之间的距离为1。如 右图中,若医院建在:
  1处,则距离和=4+12+2*20+2*40=136
  3处,则距离和=4*2+13+20+40=81
    ………….

Input

第一行一个整数n,表示树的结点数。(n<=100)
接下来的n行每行描述了一个结点的状况,包含三个整数,整数之间用空格(一个或多个)分隔,其中:第一个数为居民人口数;第二个数为左链接,为0表示无链接;第三个数为右链接。  

Output

一个整数,表示最小距离和。

Sample Input

5
13 2 3
4 0 0
12 4 5
20 0 0
40 0 0
Sample Output

81

题解:

标记距离为1,算距离时乘以人数。

代码:

var  a:array[0..200,0..200] of longint;  b:array[1..100] of longint;  n,x,y,i,j,k,sum:longint;begin  readln(n);  for i:=1 to n do    for j:=1 to n do      a[i,j]:=100000000;  for i:=1 to n do    begin      readln(b[i],x,y);      a[i,x]:=1;      a[x,i]:=1;      a[i,y]:=1;      a[y,i]:=1;    end;  for k:=1 to n do    for i:=1 to n do      for j:=1 to n do        if (i<>j)and(i<>k)and(j<>k) then          if a[i,j]>a[i,k]+a[k,j] then            a[i,j]:=a[i,k]+a[k,j];  sum:=1000000;  for i:=1 to n do    begin      x:=0;      for j:=1 to n do        if i<>j then          x:=b[j]*a[i,j]+x;      if x<sum then sum:=x;    end;  writeln(sum);end.
1 0
原创粉丝点击