时间限制: 1 Sec 内存限制: 128 MB
题目描述
设有一棵二叉树(如下图所示),其中圈中的数字表示结点中居民的人口,圈边上数字表示结点编号。现在要求在某个结点上建立一个医院,使所有居民所走的路程之和为最小,同时约定,相邻结点之间的距离为1。就本图而言,若医院建在1处,则距离和=4+12+2*20+2*40=136;若医院建在3处,则距离和=4*2+13+20+40=81……
输入
输入数据有多行,其中第一行一个整数n,表示树的结点数(n<=100)。接下来的n行每行描述了一个结点的状况,包含三个整数,整数之间用空格(一个或多个)分隔,其中:第一个数为居民人口数;第二个数为左链接,为0表示无链接;第三个数为右链接,为0表示无链接。
输出
输出只有一个整数,表示最小距离和。
样例输入
5 13 2 3 4 0 0 12 4 5 20 0 0 40 0 0
样例输出
81
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int minx = 0x3f3f3f3f;
int m = 0;
struct node{
int num;
int fa, lch, rch;
}tree[105];
bool point[105];
void DFS(int x, int step){
point[x] = 1;
m += step * tree[x].num;
if( tree[x].lch && !point[tree[x].lch] ) DFS(tree[x].lch,step+1);
if( tree[x].rch && !point[tree[x].rch] ) DFS(tree[x].rch,step+1);
if( tree[x].fa && !point[tree[x].fa] ) DFS(tree[x].fa,step+1);
return;
}
int main(){
int n;
cin>>n;
for(int i = 1;i <= n ;i++){
cin>>tree[i].num>>tree[i].lch>>tree[i].rch;
tree[tree[i].lch].fa = i;
tree[tree[i].rch].fa = i;
}
for(int i = 1;i <= n;i++){
memset(point,0,sizeof(point));
DFS(i,0);
minx = min(minx,m);
m = 0;
}
cout<<minx;
}
...