1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 101, M = 2 * N; int n, u, v, h[N], w[M], e[M], ne[M], idx; int ans = 1e9; bool visited[N]; struct node { int u, s; node() {} node(int idx, int step) : u(idx), s(step) {} }; node q[N]; void add(int u, int v) { e[idx] = v, ne[idx] = h[u], h[u] = idx++; } int bfs(int x) { int sum = 0; memset(visited, false, n + 1); visited[x] = true; int hh = 0, tt = -1; q[++tt] = node(x, 1); while (hh <= tt) { auto[u, s] = q[hh++]; for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (visited[v]) continue; q[++tt] = node(v, s + 1); visited[v] = true; sum += w[v] * s; } } return sum; } int main() { scanf("%d", &n); memset(h, -1, (n + 1) * 4); for (int i = 1; i <= n; ++i) { scanf("%d%d%d", &w[i], &u, &v); if (u) add(i, u), add(u, i); if (v) add(i, v), add(v, i); } for (int i = 1; i <= n; ++i) ans = min(ans, bfs(i)); printf("%d\n", ans); return 0; }
|