You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.2 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
2 years ago
const int INF = 0x3f3f3f3f;
2 years ago
int n;
2 years ago
int a[N], st[N]; // b 数组存是否遍历过这个节点
int e[N][10]; // 存储树
int dis[N][N]; // 存节点间的距离
2 years ago
int cnt;
void dfs(int u, int x) { // x 表示起点
2 years ago
st[u] = 1;
2 years ago
dis[x][u] = cnt, dis[u][x] = cnt;
cnt++;
for (int i = 1; i <= e[u][0]; i++) { // 枚举子节点
2 years ago
if (st[e[u][i]]) continue;
dfs(e[u][i], x);
2 years ago
}
cnt--; // 退回上一个节点,要记得把距离减去一
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
int x, y;
cin >> a[i] >> x >> y;
2 years ago
if (x) e[i][++e[i][0]] = x, e[x][++e[x][0]] = i; // 存图
if (y) e[i][++e[i][0]] = y, e[y][++e[y][0]] = i;
2 years ago
}
for (int i = 1; i <= n; i++) {
2 years ago
memset(st, 0, sizeof st);
2 years ago
cnt = 0; // 初始化
dfs(i, i); // 搜索
}
2 years ago
int ans = INF;
2 years ago
for (int i = 1; i <= n; i++) {
2 years ago
int s = 0;
2 years ago
for (int j = 1; j <= n; j++)
2 years ago
s = s + a[j] * dis[i][j]; // 累加距离
ans = min(ans, s);
2 years ago
}
2 years ago
cout << ans << endl;
2 years ago
return 0;
}