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.

51 lines
1.4 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
2 years ago
const int N = 110, M = N << 1;
2 years ago
const int INF = 0x3f3f3f3f;
2 years ago
int n;
2 years ago
int x[N]; // 点权权值数组
int st[N]; // st 数组存是否遍历过这个节点
int dis[N][N]; // 存节点间的距离
2 years ago
2 years ago
// 链式前向星
int e[M], h[N], idx, w[M], ne[M];
void add(int a, int b, int c = 0) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
void dfs(int root, int u, int step) { // root 表示根,u:当前走到哪个节点step:到u点时走了几步
st[u] = 1; // u走过了防止回头路
dis[root][u] = step, dis[u][root] = step; // root<->u之间的路径长度
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (st[v]) continue;
dfs(root, v, step + 1);
2 years ago
}
}
int main() {
2 years ago
// 初始化链式前向星
memset(h, -1, sizeof h);
2 years ago
cin >> n;
for (int i = 1; i <= n; i++) {
2 years ago
int a, b;
cin >> x[i] >> a >> b;
if (a) add(i, a), add(a, i); // 存图
if (b) add(i, b), add(b, i);
2 years ago
}
for (int i = 1; i <= n; i++) {
2 years ago
memset(st, 0, sizeof st);
2 years ago
dfs(i, i, 0); // 搜索
2 years ago
}
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 + x[j] * dis[i][j]; // 累加距离
2 years ago
ans = min(ans, s);
2 years ago
}
2 years ago
cout << ans << endl;
2 years ago
return 0;
}