洛谷P1364
#include<bits/stdc++.h>
using namespace std;
struct node{
int value, left, right, p;
node(int v, int l, int r): left(l), right(r), value(v){}
node() {}
}t[10010];
int vis[105];
int cal(int x, int d) {
if (!x || vis[x]) return 0;
vis[x] = 1;
return cal(t[x].left, d+1) + cal(t[x].right, d+1) + cal(t[x].p, d+1) + t[x].value*d;
}
//遞迴計算,若被訪問過或沒有改節點返回,然後計算父節點,左右子節點。
int main() {
int ans = 0xfffffff;
int n; cin >> n;
for (int i = 1; i <= n; i++) {
int v, l, r;
cin >> v >> l >> r;
t[i] = node(v, l, r);
}
for (int i = 1; i <= n; i++) {
t[t[i].left].p = i;
t[t[i].right].p = i;
}
for (int i = 1; i <= n; i++) {
memset(vis, 0, sizeof(vis));
ans = min(ans, cal(i, 0));
}
cout << ans;
}