#include <iostream>
#include <cstring>
using namespace std;
const int N = 110, M = 2 * N, INF = 1e9;
int n;
int cnt[N]; //cnt用来存每个村的人口
int h[N], e[M], ne[M], idx; //邻接表
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int dfs(int u, int father, int dist) //当前为u节点,u节点从哪个节点来,当前节点与根节点的距离
{
int sum = cnt[u] * dist; //当前点的值 = 人数 * 与根节点的距离
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (j == father) continue; //不走回头路
sum += dfs(j, u, dist + 1); //下一节点为j,从u过去,距离加1
}
return sum;
}
int main()
{
cin >> n;
memset(h, -1, sizeof h);
for (int i = 1; i <= n; i ++ )
{
int l, r;
cin >> cnt[i] >> l >> r; //读入每个节点人数、左儿子和右儿子
if (l) add(i, l), add(l, i); //儿子节点不为空才建立无向边
if (r) add(i, r), add(r, i);
}
int res = INF; //遍历找出最小值
for (int i = 1; i <= n; i ++ ) res = min(res, dfs(i, -1, 0));
cout << res << endl;
return 0;
}
您好,我想请问下dfs不需要终止条件吗?