难度:3
借用了上一题的做法,就是暴力lca,先用bfs求出所有点的层数,然后暴力即可,因为数据不大,100.
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
struct node {
int w, lchild, rchild, layer;
} Node[105];
int fa[105];
void bfs(int root) {
queue<int> q;
q.push(root);
Node[root].layer = 1;
while(!q.empty()) {
int now = q.front();
q.pop();
if (Node[now].lchild != -1) {
q.push(Node[now].lchild);
Node[Node[now].lchild].layer = Node[now].layer + 1;
}
if (Node[now].rchild != -1) {
q.push(Node[now].rchild);
Node[Node[now].rchild].layer = Node[now].layer + 1;
}
}
}
int solve(int a, int b) {
while (Node[a].layer != Node[b].layer) {
if (Node[a].layer > Node[b].layer) a = fa[a];
else b = fa[b];
}
while (a != b) {
a = fa[a];
b = fa[b];
}
return a;
}
int main() {
int n;
cin >> n;
int Hash[105] = {};
for (int i = 0; i < n; i++) {
int w, u, v;
cin >> w >> u >> v;
Node[i + 1].w = w;
if (u == 0) {
Node[i + 1].lchild = -1;
} else {
fa[u] = i + 1;
Node[i + 1].lchild = u;
Hash[u]++;
}
if (v == 0) {
Node[i + 1].rchild = -1;
} else {
fa[v] = i + 1;
Node[i + 1].rchild = v;
Hash[v]++;
}
}
int root;
for (int i = 1; i <= n; i++) {
if (Hash[i] == 0) root = i;
}
fa[root] = root;
bfs(root);
int ans = 1000000000;
for (int i = 1; i <= n; i++) {
int temp = 0;
for (int j = 1; j <= n; j++) {
int lca = solve(i, j);
temp += Node[j].w * (Node[i].layer + Node[j].layer - Node[lca].layer * 2);
}
if (temp < ans) ans = temp;
}
cout << ans;
return 0;
}