医院设置

来源:互联网 发布:全球网络电视 编辑:程序博客网 时间:2024/04/27 18:58

医院设置

Time Limit:10000MS  Memory Limit:65536K
Total Submit:101 Accepted:77
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 


  • var   f:array [0..101,0..101] of longint;   a:array [0..101] of longint;   i,j,k,n,ans,min,x,y:longint;begin     readln(n);     for i:=1 to n do         for j:=1 to n do f[i,j]:=maxlongint div 3;     for i:=1 to n do         begin             readln(a[i],x,y);             if x<>0 then f[x,i]:=1; f[i,x]:=1;             if y<>0 then f[y,i]:=1; f[i,y]:=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 (k<>j) then                    if f[i,k]+f[k,j]<f[i,j] then f[i,j]:=f[i,k]+f[k,j];     min:=maxlongint-1;     for i:=1 to n do         begin             ans:=0;             for j:=1 to n do                 if i<>j then ans:=ans+a[j]*f[i,j];             if ans<min then min:=ans;         end;     writeln(min);end.

0 1