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
| #include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn=2e5+10,inf=0x3f3f3f3f,mod=1000000007; const int maxl=30; vector<int> G[maxn]; int gene[maxn][maxl],depth[maxn],lg[maxn],dfn[maxn],tim=0; void dfs(int x,int fa) { if(!dfn[x]) dfn[x]=++tim; depth[x]=depth[fa]+1; gene[x][0]=fa; for(int i=1;(1<<i)<=depth[x];i++) gene[x][i]=gene[gene[x][i-1]][i-1]; for(int i=0;i<G[x].size();i++) if(G[x][i]!=fa) dfs(G[x][i],x); } int lca(int x,int y) { if(depth[x]<depth[y]) swap(x,y); while(depth[x]>depth[y]) x=gene[x][lg[depth[x]-depth[y]-1]]; if(x==y) return x; for(int i=lg[depth[x]];i>=0;i--) if(gene[x][i]!=gene[y][i]) { x=gene[x][i]; y=gene[y][i]; } return gene[x][0]; } int dist(int x,int y) { int tem=lca(x,y); return (int)(abs(depth[x]-depth[tem])+abs(depth[y]-depth[tem])); } void init(int s,int n) { depth[s]=1; for(int i=1;i<=n;i++) lg[i]=lg[i-1]+((1<<(lg[i-1]+1))==i); dfs(s,s); } int stk[maxn],top; vector<int>g[maxn]; map<int,bool>vis; void build(vector<int> &rec,int n) { sort(rec.begin(),rec.end(),[](const int &x,const int &y){ return dfn[x]<dfn[y]; }); stk[top=1]=rec[0]; g[1].clear(); auto adde = [](int u,int v) { g[u].push_back(v); }; for(int i=1;i<rec.size();i++) { int now=rec[i]; int lc=lca(now,stk[top]); while(top>1&&dfn[lc]<=dfn[stk[top-1]]) { adde(stk[top-1],stk[top]); top--; } if(dfn[lc]<dfn[stk[top]]) { g[lc].clear(); adde(lc,stk[top]); stk[top]=lc; } g[now].clear(); stk[++top]=now; } while(--top) adde(stk[top],stk[top+1]); } int dp[maxn],f[maxn]; void dfs2(int x) { dp[x]=f[x]=0; for(int &v:g[x]) { dfs2(v); dp[x]+=dp[v]; f[x]+=f[v]; } if(vis[x]) { dp[x]+=f[x]; f[x]=1; } else if(f[x]>1) { dp[x]++; f[x]=0; } } signed main(signed argc, char const *argv[]) { int n,u,v,q,k; scanf("%d",&n); for(int i=1;i<n;i++) { scanf("%d%d",&u,&v); G[u].push_back(v); G[v].push_back(u); } init(1,n); scanf("%d",&q); while(q--) { scanf("%d",&k); vector<int>rec; vis.clear(); bool ok=1,ok1=0; for(int i=1;i<=k;i++) { scanf("%d",&u); if(u==1) ok1=1; vis[u]=true; rec.push_back(u); } for(int &x:rec) if(x!=1&&vis[gene[x][0]]) { ok=0; break; } if(!ok) { printf("-1\n"); continue; } if(!ok1) rec.push_back(1); build(rec,n); dfs2(1); printf("%d\n",dp[1]); } return 0; }
|