[LUOGU] 1364 Hospital Settings

There is a binary tree, as shown in the figure:

 [I am the picture]

Among them, the numbers in the circle represent the population of the residents in the node.Numbers on the rim represent node numbers. A hospital is now required on a node to minimize the sum of all residents'journeys, and it is agreed that the distance between adjacent nodes is 1.As in the figure above,

If the hospital is located in one place, the distance and = 4+12+2*20+2*40=136; if the hospital is located in three places, the distance and = 4*2+13+20+40=81...

Input and Output Formats

Input format:
The first row is an integer n, which represents the number of nodes in the tree.(n < 100)

The next n rows describe the condition of a node, consisting of three integers separated by a space (one or more), where the first number is the population of the resident; the second number is the left link, with 0 indicating no link; and the third number is the right link.

Output format:
An integer representing the minimum distance sum.

Input and Output Samples

Input Sample#1: Copy
5                       
13 2 3
4 0 0
12 4 5
20 0 0
40 0 0
 Output Sample#1: Copy
81

With each node as the hospital, the distances are enumerated.(floyd?)
Incidental adjacency table.

//Writer:GhostCai && His Yellow Duck

#include<iostream>
#include<cstring>
#define MAXN 2000
using namespace std;


//
struct edge{
    int to,next;
}e[MAXN];

int cnt,head[MAXN];

void add(int x,int y){
    e[++cnt].to = y;
    e[cnt].next = head[x];
    head[x]=cnt;
} 
//

int n,ans=1<<30;
int dis[MAXN],num[MAXN];
bool vis[MAXN];

void dfs(int id,int dp){
    int i;
    for(i=head[id];i!=-1;i=e[i].next){
        if(!e[i].to || vis[e[i].to ]) continue;
        vis[e[i].to ]=1;
        dis[e[i].to] = dp+1;
        dfs(e[i].to , dp+1);
    }
}

int main(){
    cin>>n;
    int i,j,x,y;
    memset(head,-1,sizeof(head));
    for(i=1;i<=n;i++){
        cin>>num[i]>>x>>y;
        add(i,x);add(x,i);
        add(i,y);add(y,i);
    }
    for(i=1;i<=n;i++){
        memset(dis,0,sizeof(dis));
        memset(vis,0,sizeof(vis));
        vis[i]=1;//!!!
        dfs(i,0);
        int sum=0;
        for(j=1;j<=n;j++){
            sum+=num[j]*dis[j];
        }
        ans=min(sum,ans);
    }
    cout<<ans<<endl;
    return 0;
}

Posted by dan7474 on Mon, 20 Jul 2020 08:11:24 -0700