题解
2026-06-01 13:47:54
发布于:浙江
5阅读
0回复
0点赞
大家好,我是энтджей,今天是我2026年第十三次正式发题解!
能不能点个赞
首先简化题意:
- 其实就是寻找有没有一条链可以串连所有的宝藏
然后就是写代码
-
处理输入(read):
- 正常输入
-
核心部分(process):
- 寻找任意有宝藏的结点,寻找存不存在一条可以串连所有的宝藏
-
最后输出(write):
- 输出判断结果
其实有点抽象,我太挫了,讲不来
完整代码:
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5;
int T;
int n;
int cnt = 0;
int a[N];
vector<int> ve[N];
bool flag = false;
void init() {
memset(a, 0, sizeof a);
for(int i = 0; i < n; i++) {
ve[i].clear();
}
cnt = 0;
flag = false;
}
void read() {
cin >> n;
for(int i = 1; i <= n; i++) {
cin >> a[i];
cnt += a[i];
}
for(int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
ve[x].push_back(y);
ve[y].push_back(x);
}
}
int dfs(int id, int fa, int sum){
//return -1: 有解
//return 0 : 当前子树没有宝物
//return 1 : 当前子树有宝物
//return 2 : 无解
sum += a[id];
if(sum == cnt){
return -1;
}
int HasTree = 0;
for( auto i : ve[id] ) {
if(i != fa) {
int t = dfs(i, id, sum);
if(t == -1) return -1;
HasTree += (t == 1 ? 1 : 0);
if(HasTree > 1 || t == 2) {
return 2;
}
}
}
return (HasTree + a[id] > 0) ? 1 : 0;
}
void process() {
for(int i = 1; i <= n; i++){
if(a[i]){
if(dfs(i, 0, 0) == -1) {
flag = true;
break;
}
}
}
}
void write() {
cout << ((flag == true) ? "Yes" : "No") << endl;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin >> T;
while(T--) {
init();
read();
process();
write();
}
return 0;
}
🎉完结撒花🎉
这里空空如也






有帮助,赞一个