"Example 3-3" Hospital settings
Time limit: Ms Memory limit: 65536 KB
Number of submissions: 150 by Number: 106
"Title description"
There is a binary tree (as shown in Figure 3-8, where the number in the circle represents the population of the node, and the number on the edge of the circle indicates the node number. It is now required to establish a hospital on a node that minimizes the sum of the distances travelled by all inhabitants, while agreeing that the distance between adjacent nodes is 1. For the purpose of this picture, if the hospital is built at 1, then the distance and =4+12+2*20+2*40=136, and if the hospital is built at 3, the distance and the =4*2+13+20+40=81 ...
"Input"
The first line is an integer n, which represents the node number (n≤100) of the tree. The next n rows each row describes the condition of a node, consisting of three integers, separated by spaces (one or more), where: The first number is the number of inhabitants, the second number is the left link, 0 is no link, the third number is the right link, and 0 means no link. "Output"
An integer that represents the minimum distance and. "Input Sample"
5
2 3
4 0 0 4 5
0 0 40
0 0
"output Example"
81
"Code Implementation"
#include <bits/stdc++.h>
using namespace std;
int main ()
{
int n,l,r;
int a[105][105],b[105];
cin>>n;
for (int i=1;i<=n;i++) for
(int j=1;j<=n;j++)
a[i][j]=999999999;
for (int i=1;i<=n;i++)
{
a[i][i]=0;
cin>>b[i]>>l>>r;
if (l>0) a[i][l]=a[l][i]=1;//establishes the adjacency matrix
if (r>0) a[i][r]=a[r][i]=1;
}
for (int k=1;k<=n;k++) for
(int i=1;i<=n;i++)
if (i!=k) for
(int j=1;j<=n;j++)
if (j!=i &&J!=K&&A[I][K]+A[K][J]<A[I][J])//floyed Two node minimum distance, that is, now a[i][j] save I to J shortest distance
A[i][j]=a[i][k] +A[K][J];
int minn=999999999;
for (int i=1;i<=n;i++)//enumeration
{
int sum=0;
for (int j=1;j<=n;j++)
sum+=a[i][j]*b[j];
if (Sum<minn)
minn=sum;
}
cout<<minn<<endl;
return 0;
}