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 82 83 84 85 86 87 88 89 90 91 92 93
| #include <bits/stdc++.h> const int N = 1e5 + 100, D = 18; int n, num = 0, q, k, ans; int a[N], si[N]; struct Edge{ int ne, ver; } e[N << 1], ef[N << 1]; int h[N], idx = 0, hf[N], idf = 0; int f[N][D], dep[N], dfn[N]; int stk[N], top; void add(int x, int y){ e[idx] = {h[x], y}, h[x] = idx++; } void adf(int x, int y){ ef[idf] = {hf[x], y}, hf[x] = idf++; } void dfs1(int x, int fa) { dfn[x] = ++num, f[x][0] = fa, dep[x] = dep[fa] + 1; for (int i = h[x]; ~i; i = e[i].ne) if (e[i].ver != fa) dfs1(e[i].ver, x); } int lca(int x, int y) { if (dep[x] > dep[y]) std::swap(x, y); for (int i = D - 1; ~i; --i) if (dep[f[y][i]] >= dep[x]) y = f[y][i]; if (x == y) return x; for (int i = D - 1; ~i; --i) if (f[y][i] != f[x][i]) y = f[y][i], x = f[x][i]; return f[x][0]; } void ins(int x) { if (!top) return void(stk[++top] = x); int z = lca(x, stk[top]); for (; top > 1 && dep[z] < dep[stk[top - 1]]; --top) adf(stk[top - 1], stk[top]); if (dep[z] < dep[stk[top]]) adf(z, stk[top--]); if (!top || stk[top] != z) stk[++top] = z; stk[++top] = x; } void dfs2(int x) { if (si[x]) for (int i = hf[x], y; ~i; i = ef[i].ne) { dfs2(y = ef[i].ver); if (si[y]) si[y] = 0, ++ans; } else { for (int i = hf[x], y; ~i; i = ef[i].ne) { dfs2(y = ef[i].ver); si[x] += si[y]; si[y] = 0; } if (si[x] > 1) si[x] = 0, ++ans; } hf[x] = -1; } void work() { std::sort(a + 1, a + k + 1, [&](int x, int y){ return dfn[x] < dfn[y]; }); top = ans = idf = 0; if (a[1] != 1) stk[++top] = 1; for (int i = 1; i <= k; ++i) ins(a[i]); for (; top > 1; --top) adf(stk[top - 1], stk[top]); dfs2(1), si[1] = 0; printf("%d\n", ans); } int main() { memset(h, -1, sizeof h), memset(hf, -1, sizeof hf); scanf("%d", &n); for (int i = 1, u, v; i < n; ++i) { scanf("%d %d", &u, &v); add(u, v), add(v, u); } dfs1(1, 0); for (int j = 1; j < D; ++j) for (int i = 1; i <= n; ++i) f[i][j] = f[f[i][j - 1]][j - 1]; for (scanf("%d", &q); q--; ) { scanf("%d", &k); for (int i = 1; i <= k; ++i) { scanf("%d", &a[i]); si[a[i]] = 1; } for (int i = 1; i <= k; ++i) if (si[f[a[i]][0]]) { puts("-1"); while(k) si[a[k--]] = 0; break; } if (!k) continue; work(); } return 0; }
|