题解 | 树上寻宝

树上寻宝

https://www.nowcoder.com/practice/855daae6f07b472e86327b910da0bcb2

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define ALL(a) a.begin(),a.end() 
const ll N = 1e5 + 7, M = 5;
struct p { int t, w; };
int n1[N];
bool vis[N];
vector<int> n2[N];
int main() {
	istream::sync_with_stdio(0), cin.tie(0);
	int n, k;cin >> n >> k;
	ll ans = 0;
	for (int i = 1;i <= n;++i) cin >> n1[i];
	for (int i = 0;i < n - 1;++i) {
		int u, v;cin >> u >> v;
		n2[u].push_back(v), n2[v].push_back(u);
	}
	queue<p> q;
	q.push({1, 0});
	vis[1] = 1;
	while (q.size()) {
		p tp = q.front();q.pop();
		if (tp.w > 2 * k) break;
		ans += n1[tp.t];
		for (int v : n2[tp.t]) if(!vis[v]) vis[v] = 1, q.push({v, tp.w + 1});
	}
	cout << ans;
	return 0;
}

全部评论

相关推荐

二十岁的编程男神王大...:读博吧兄弟,你这绩点太好了,何必转码,另外哈哈哈真见到有括号标出来985的,这个不标注也知道吧
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务