思路
因为这些点要么在同一条路径上,要么相差1,所以把所有点向上移动一格,那么它们应该都在一条路径上。
如何判断在一条路径上?我的方法是按深度从下到上,判断下面结点的祖先是不是上面结点。所以用到了倍增发求LCA。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
#define inf 0x3f3f3f3f
const int N = 2e5 + 10;
vector<int> np[N];
int dep[N];
int up[N][100];
int arr[N];
void init(int p, int fa, int d) {
up[p][0] = fa;
dep[p] = d;
for(int nt : np[p]) {
if(nt == fa) continue;
init(nt, p, d + 1);
}
}
bool cmp(int a, int b) {
return dep[a] > dep[b];
}
int lca(int a, int b) { //a >= b
int d = dep[a] - dep[b];
for(int i = 0; (1 << i) <= d; i++) {
if((1 << i) & d) a = up[a][i];
}
if(a != b) {
for(int i = 31; i >= 0; i--) {
if(up[a][i] != up[b][i]) {
a = up[a][i];
b = up[b][i];
}
}
a = up[a][0];
}
return a;
}
int main() {
ios::sync_with_stdio(false);
int n, m;
cin >> n >> m;
for(int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
np[u].push_back(v);
np[v].push_back(u);
}
init(1, 0, 1);
for(int k = 1; k <= 31; k++) {
for(int i = 1; i <= n; i++) {
up[i][k] = up[up[i][k - 1]][k - 1];
}
}
while(m--) {
int k;
cin >> k;
for(int i = 0; i < k; i++) {
cin >> arr[i];
}
sort(arr, arr + k, cmp);
bool ok = true;
for(int i = 0; i < k; i++) {
if(arr[i] != 1)
arr[i] = up[arr[i]][0];
}
k = unique(arr, arr + k) - arr;
int a = arr[0];
if(ok)
for(int i = 1; i < k; i++) {
int b = arr[i];
int f = lca(a, b);
//cout << a << " " << b << " " << f << endl;
if(f != b) {
ok = false;
//break;
}
a = b;
}
if(ok) cout << "YES" << endl;
else cout << "NO" << endl;
}
}