bfs求调,#5 WA
查看原帖
bfs求调,#5 WA
592342
WA_automat楼主2022/8/18 00:21
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int n, u, v;
int h[N], e[N], ne[N], w[N], idx;
bool st[N];
void add(int a, int b) {
	e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
int bfs(int x) {
	memset(st, false, sizeof st);
	int mark = 0, res = 0;
	queue<PII> q;
	q.push({ x,mark });
	st[x] = true;
	while (!q.empty()) {
		auto item = q.front();
		q.pop();
		res += w[item.first] * item.second;
		for (int i = h[item.first]; i != -1; i = ne[i]) {
			int j = e[i];
			if (!st[j]) {
				st[j] = true;
				q.push({ j,item.second + 1 });
			}
		}
	}
	return res;
}
int main(void) {
	cin >> n;
	memset(h, -1, sizeof h);
	for (int i = 1; i <= n; ++i) {
		cin >> w[i] >> u >> v;
		if (u) add(i, u), add(u, i);
		if (v) add(i, v), add(v, i);
	}
	int ans = 0x3f3f3f3f;
	for (int i = 1; i <= n; ++i) {
		ans = min(ans, bfs(i));
	}
	cout << ans;
	return 0;
}
2022/8/18 00:21
加载中...