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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
| #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, q;
int k[N], b[N];
int cnt, head[N];
struct edge { int to, nxt; edge(int v = 0, int x = 0) : to(v), nxt(x) {} };
edge e[N << 1];
void add(int u, int v) { e[++cnt] = edge(v, head[u]); head[u] = cnt; e[++cnt] = edge(u, head[v]); head[v] = cnt; }
int tim, dfn[N];
int depth[N], top[N], son[N], siz[N], fa[N];
void dfs1(int x, int father) { dfn[x] = ++tim; fa[x] = father; depth[x] = depth[fa[x]] + 1; siz[x] = 1; for(int i = head[x]; i; i = e[i].nxt) { int v = e[i].to; if(v == fa[x])continue; dfs1(v, x); siz[x] += siz[v]; if(siz[v] > siz[son[x]]) son[x] = v; } }
void dfs2(int x, int topfather) { top[x] = topfather; if(!son[x])return; dfs2(son[x], topfather); for(int i = head[x]; i; i = e[i].nxt) { int v = e[i].to; if(v == fa[x] || v == son[x]) continue; dfs2(v, v); } }
int LCA(int x, int y) { while(top[x] != top[y]) { if(depth[top[x]] < depth[top[y]]) swap(x, y); x = fa[top[x]]; } if(depth[x] > depth[y]) swap(x, y); return x; }
int st[N], t;
int f[N], h[N], c[N];
vector <int> g[N];
void link(int x, int y) { g[x].push_back(y); }
void clear(int x) { f[x] = h[x] = c[x] = 0; g[x].clear(); }
void insert(int x) { if(st[t] == x)return; int lca = LCA(st[t], x); if(lca != st[t]) { while(dfn[lca] < dfn[st[t - 1]]) link(st[t - 1], st[t]), t--; if(dfn[lca] > dfn[st[t - 1]]) clear(lca), link(lca, st[t]), st[t] = lca; else link(lca, st[t--]); } st[++t] = x; clear(x); }
bool cmp(int x, int y) { return dfn[x] < dfn[y]; }
void build(int n) { sort(k + 1, k + n + 1, cmp); t = 0; st[++t] = 1; clear(1); for(int i = 1; i <= n; i++) insert(k[i]); for(int i = 1; i < t; i++) link(st[i], st[i + 1]); }
void dp(int x, int fa) { for(auto v : g[x]) { dp(v, x); f[x] += f[v]; h[x] += h[v]; } if(f[x] == -1)return; if(b[x])f[x] += h[x], h[x] = 1; else if(h[x] > 1)f[x]++, h[x] = 0; }
int main() { scanf("%d", &n); for(int i = 1; i < n; i++) { int x, y; scanf("%d%d", &x, &y); add(x, y); } dfs1(1, 0); dfs2(1, 0); scanf("%d", &q); for(int i = 1; i <= q; i++) { int m; scanf("%d", &m); for(int j = 1; j <= m; j++) scanf("%d", &k[j]), b[k[j]] = 1; bool flag = true; for(int j = 1; j <= m; j++) { if(b[fa[k[j]]] && k[j] != 1) { printf("-1\n"); flag = false; break; } } if(flag){build(m); dp(1, 0); printf("%d\n", f[1]);} for(int j = 1; j <= m; j++) b[k[j]] = 0; } return 0; }
|