医院设置-SSL 1614

来源:互联网 发布:swot分析软件 编辑:程序博客网 时间:2024/05/09 22:00
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 Output81 题解:这道题用最短路的方法做。const  maxn=100;var  n,i,j,k,left,right,ans,tot:longint;  a:array[1..maxn,1..maxn] of longint;  b:array[1..maxn] of longint;begin  readln(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],left,right);      if left>0 then begin a[left,i]:=1;a[i,left]:=1;end;      if right>0 then begin a[right,i]:=1;a[i,right]:=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[j,k]<a[i,j])          then a[i,j]:=a[i,k]+a[j,k];       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
原创粉丝点击