http://codeforces.com/contest/1328/problem/E
题意:
一棵树,有m个询问,每次询问询问k个点是否都在一条从根节点(点1)到某个节点v的路径上,或者距离这条路径的距离为1也可以。
首先先解决判断所给的点是否都在一条从根节点到某个点的路径上这个问题:
可以参考倍增求lca的方法,判断某个点是否为另外一个点的祖先,每次判断两个点,并且保存更深的那个点(使用更深的那个点作为下次判断的其中一个点)。这样不断判断,若出现任何一组点不存在组先关系,则该组点不都在同一个路径上。
本题若是某个点距离该路径长度为1也算符合条件,则只需要在每次取点的时候取的是点的父亲节点即可。假如某个点位于路径上,则其父亲依然在路径上,假如某个点距离路径距离为1,则其父亲也在路径上,若某个点距离路径距离大于1,则其父亲不在路径上
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 2e5 + 7;
int Head[maxn], Nxt[maxn << 1], To[maxn << 1], fat[maxn];
int n, m, tot, id;
// anc:倍增保存组先 dep:节点深度
int anc[maxn][22], dep[maxn];
void add(int fro, int to) {
Nxt[++tot] = Head[fro];
To[tot] = to;
Head[fro] = tot;
}
queue<int> Q;
void bfs(int now) {
Q.push(now);
dep[now] = 1;
while (!Q.empty()) {
int now = Q.front();
Q.pop();
for (int i = Head[now]; i; i = Nxt[i]) {
const int &to = To[i];
if (dep[to])
continue;
dep[to] = dep[now] + 1;
fat[to] = now;
anc[to][0] = now;
Q.push(to);
for (int j = 1; j <= 20; j++) {
anc[to][j] = anc[anc[to][j - 1]][j - 1];
}
}
}
}
//默认b更深
bool check(int a, int b) {
for (int i = 20; i >= 0; i--) {
if (dep[anc[b][i]] >= dep[a])
b = anc[b][i];
}
if (b == a)
return 1;
else
return 0;
}
int main() {
cin >> n >> m;
int fro, to;
for (int i = 1; i < n; i++) {
scanf("%d %d", &fro, &to);
add(fro, to);
add(to, fro);
}
bfs(1);
while (m--) {
int k, x1, x2;
scanf("%d", &k);
int ok = 1;
k--;
scanf("%d", &x1);
if (x1 != 1)
x1 = fat[x1];
while (k--) {
scanf("%d", &x2);
if (ok == 0)
continue;
if (x2 != 1)
x2 = fat[x2];
if (dep[x1] < dep[x2])
swap(x1, x2);
if (check(x2, x1) == 0)
ok = 0;
}
if (ok)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}