医院设置
医院设置 (BFS)
题目描述:
设有一颗二叉树,其中圈中数字表示节点中居民的人口,圈边上数字表示节点编号,现在要
求在某个节点上建立一个医院,使所有居民所走的路程之和为最小,同时约定,相邻节点之
间的距离为 1。
输入格式:
第一行一个整数 n,表示树的节点数(n<=1000) 。接下来的 n 行每行描述了一个节点的状况,
包含三个整数,整数之间用空格分开,其中:第一个数为居民人口数;第二个数为左链接,
为 0 表示无链接,第三个数为右链接,为 0 表示无连接
输出格式:
只有一个整数,表示最小距离和
样例输入:
5
13 2 3
4 0 0
12 4 5
20 0 0
40 0 0
样例输出:
81
代码如下:
#include <iostream>
#include <deque>
#define INF 1000000007
using namespace std;
int n;
struct tree_type
{
int p, l, r, f, d;
};
tree_type t[1000];
bool vis[1000];
deque<int> q;
int bfs(int x)
{
for (int i = 1; i <= n; ++i)
vis[i] = false;
vis[x] = true;
q.push_back(x);
t[x].d = 0;
int now;
while (!q.empty())
{
now = q.front();
q.pop_front();
if (!vis[t[now].l])
{
vis[t[now].l] = true;
t[t[now].l].d = t[now].d + 1;
q.push_back(t[now].l);
}
if (!vis[t[now].r])
{
vis[t[now].r] = true;
t[t[now].r].d = t[now].d + 1;
q.push_back(t[now].r);
}
if (!vis[t[now].f])
{
vis[t[now].f] = true;
t[t[now].f].d = t[now].d + 1;
q.push_back(t[now].f);
}
}
int ret = 0;
for (int i = 1; i <= n; ++i)
ret += t[i].p * t[i].d;
return ret;
}
int main ()
{
cin >> n;
for (int i = 1; i <= n; ++i)
{
cin >> t[i].p >> t[i].l >> t[i].r;
if (t[i].l) t[t[i].l].f = i;
if (t[i].r) t[t[i].r].f = i;
}
int ans = INF, pos, tmp;
for (int i = 1; i <= n; ++i)
{
tmp = bfs(i);
if (ans > tmp)
{
pos = i;
ans = tmp;
}
}
cout << ans << endl << pos << endl;
}