Passable Paths (easy version)

Passable Paths (easy version)

Created by LXC on Sun Aug 6 23:42:20 2023

https://codeforces.com/problemset/problem/1702/G1

ranting: 1900

tag: dfs and similar, trees

problem

给出一颗树,然后最多不超过5次查询。

每次查询一个顶点集合,求顶点中的顶点是否能组成一条简单路径,不能重复经过同一个点。

solution

每次查询用dfs,函数返回当前节点下有多少条分支。

显然次递归返回的分支数不超过2,并且如果接收到子树返回的分支数为2,那么当前节点不能存在于顶点集合中。

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

#include <bits/stdc++.h>
#define SINGLE_INPUT
#define ll long long
#define ull unsigned long long
#define N 200005
#define MOD 998244353
using namespace std;

vector<int> g[N];

void sol() {
int n;
cin >> n;
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
int q;
cin >> q;
while (q--) {
int k;
cin >> k;
set<int> st;
for (int i = 0; i < k; i++) {
int x;
cin >> x;
st.insert(x);
}
int ok = 1;
auto dfs = [&](auto& self, int x, int fa) -> int {
int cnt = 0;
for (int y : g[x]) {
if (y == fa)
continue;
int rt = self(self, y, x);
if (rt == 1)
cnt++;
else if (rt == 2) {
if (st.count(x)) {
ok = 0;
return -1;
}
cnt += 2;
} else if (rt != 0)
return -1;
}
if (cnt == 0)
return st.count(x);
if (cnt == 1 || cnt == 2)
return cnt;
ok = 0;
return -1;
};
dfs(dfs, 1, -1);
if (ok)
cout << "YES\n";
else
cout << "NO\n";
}
}

int main() {
cout << setprecision(15) << fixed;
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
#ifndef SINGLE_INPUT
int t;
cin >> t;
while (t--) {
sol();
}
#else
sol();
#endif
return 0;
}