#include <bits/stdc++.h>
using namespace std;
#define F(i, x, y) for (int i = x; i <= y; ++i)
#define U(i, y, x) for (int i = y; i >= x; --i)
#define pbk push_back
namespace IO{
template <typename T> inline void read(T &x) {
x = 0; char ch = getchar(); bool w = 1;
while (!isdigit(ch)) {
if (ch == 0x2d) w = 0;
ch = getchar();
}
while (isdigit(ch)) {
x = (x << 1) + (x << 3) + (ch ^ 0x30);
ch = getchar();
} x = w ? x : -x;
}
template <typename T> inline void write(T x) {
if (x < 0) putchar(0x2d), x = -x;
if (x > 9) write(x / 0xa);
putchar(x % 0xa + 0x30);
}
} using namespace IO;
#define N 100005
int n, q, k, h[N], vis[N];
vector<int> e[N];
int fa[N][20], dep[N], dfn[N], tim;
inline void dfs1(int x, int father) {
fa[x][0] = father; dep[x] = dep[father] + 1; dfn[x] = ++tim;
F(i, 0, 18) fa[x][i + 1] = fa[fa[x][i]][i];
F(i, 0, (int) e[x].size() - 1) {
int y = e[x][i]; if (y == father) continue;
dfs1(y, x);
}
}
inline int lca(int x, int y) {
if (dep[x] < dep[y]) swap(x, y);
U(i, 19, 0) if (dep[fa[x][i]] >= dep[y]) x = fa[x][i];
if (x == y) return x;
U(i, 19, 0) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
return fa[x][0];
}
vector<int> E[N];
int sta[N], top;
int flag;
inline int cmp(const int x, const int y) {
return dfn[x] < dfn[y];
}
inline void connect(int x, int y) {
E[x].pbk(y);
}
inline void build() {
sort(h + 1, h + k + 1, cmp); sta[top = 1] = 1;
F(i, 1, k) if (vis[fa[h[i]][0]]) return (void) (flag = 1);
F(i, 1, k) {
if (h[i] == sta[top]) continue;
int lc = lca(h[i], sta[top]);
if (lc != sta[top]) {
while (dep[sta[top - 1]] > dep[lc]) {
connect(sta[top - 1], sta[top]), --top;
}
if (sta[top - 1] == lc) connect(lc, sta[top]), --top;
else connect(lc, sta[top]), sta[top] = lc;
}
sta[++top] = h[i];
}
F(i, 1, top - 1) connect(sta[i], sta[i + 1]);
}
int tag[N];
inline int dfs2(int x) {
if (vis[x]) tag[x] = 1;
else tag[x] = 0;
int cnt = 0, res = 0;
F(i, 0, (int) E[x].size() - 1) {
int y = E[x][i]; res+= dfs2(y);
cnt+= tag[y];
}
if (vis[x]) res+= cnt;
else if (cnt > 1) ++res, tag[x] = 0;
else if (cnt == 1) tag[x] = 1;
return res;
}
inline void cls(int x) {
F(i, 0, (int) E[x].size() - 1) {
cls(E[x][i]);
} E[x].clear(); tag[x] = 0;
}
inline void clean() {
F(i, 1, k) vis[h[i]] = 0;
cls(1);
}
void init() {
read(n); int x, y;
F(i, 2, n) read(x), read(y), e[x].pbk(y), e[y].pbk(x);
dfs1(1, 0);
}
void work() {
read(q); while (q--) {
read(k); F(i, 1, k) read(h[i]), vis[h[i]] = 1;
flag = 0;
build();
if (flag) puts("-1");
else write(dfs2(1)), putchar(0xa);
clean();
}
}
int main() {
init(); work();
return 0;
}剪贴板
剪贴板 31wh8rhg
剪贴板信息
剪贴板信息
- 收录
- 更新