用一层循环枚举起点, bfs以该起点按层搜索遍历整个图,同时记录总路径。因为每个顶点只遍历一次,加上起点枚举复杂度为O(n^2)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
//#define int ll
#define mm(a) memset(a,0,sizeof(a))
#pragma warning (disable :4996);
const int N = 1e3 + 10;
const int mod = (1e9) + 7;
int T, n, m, k, q;
int a, l, r;
struct edge {
int to, dep;
};
vector<edge>gra[N];
int pw[N];
int vis[N] = { 0 };
int g[N][N];
int bfs(int s) {
mm(vis);
queue<edge>q;
q.push({ s,0 });
int sum = 0;
while (!q.empty()) {
edge now = q.front();
q.pop();
vis[now.to]=1;
for(auto x:gra[now.to]){
int to=x.to;
if(!vis[to]){
edge nx={to,now.dep+1};
q.push(nx);
vis[to]=1;
sum+=(nx.dep*pw[to]);
}
}
}
return sum;
}
signed main() {
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
//freopen("out.txt", "w", stdout);
#endif
cin >> n;
for (int i= 1; i <= n; i++) {
cin >> a >> l >> r;
pw[i] = a;
if(l)gra[i].push_back({l,0}),gra[l].push_back({i,0});
if(r)gra[i].push_back({r,0}),gra[r].push_back({i,0});
}
int ans = INT_MAX;
for (int j = 1; j <= n; j++) {
ans = min(ans, bfs(j));
}
cout << ans;
}