医院设置

来源:互联网 发布:知乎银杏湖乐园好玩吗 编辑:程序博客网 时间:2024/06/08 13:47

医院设置

Time Limit:10000MS  Memory Limit:65536K
Total Submit:95 Accepted:71
Case Time Limit:1000MS

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 

Source

elba

 

 

var  n,i,j,k,ans,l,r,tot:longint;  a:array[1..100,1..100]of longint;  b:array[1..100]of longint;begin  read(n);  for i:=1 to n do  for j:=1 to n do a[i,j]:=10000;  for i:=1 to n do   begin    a[i,i]:=0;    read(b[i],l,r);    if l>0 then begin a[l,i]:=1;a[i,l]:=1;end;    if r>0 then begin a[r,i]:=1;a[i,r]:=1;end;   end;  for k:=1 to n do   begin    for i:=1 to n do     if i<>k then      begin       for j:=1 to n do        if(k<>j)and(i<>j)and(a[i,k]+a[k,j]<a[i,j]) then a[i,j]:=a[i,k]+a[k,j];      end;    end;  ans:=maxlongint;  for i:=1 to n do   begin    tot:=0;    for j:=1 to n do     inc(tot,a[i,j]*b[j]);    if tot<ans then ans:=tot;  end;  writeln(ans);end.

 

0 0