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
| #include<bits/stdc++.h> using namespace std; const int N=4e5+5,mod=1e9+7; int n,q,x,y,k,tot,a[N],fa[N],val[N],sz[N],dep[N],f[N][25],tim,dfn[N],ans; vector<int>v[N]; int find(int x){ return x==fa[x]?x:fa[x]=find(fa[x]); } void dfs(int x){ sz[x]=x<=n,dfn[x]=++tim; for(int i=0;i<=19;i++) f[x][i+1]=f[f[x][i]][i]; for(int y:v[x]) f[y][0]=x,dep[y]=dep[x]+1,dfs(y),sz[x]+=sz[y]; } int lca(int x,int y){ if(dep[x]<dep[y]) swap(x,y); for(int i=20;i>=0;i--) if(dep[f[x][i]]>=dep[y]) x=f[x][i]; if(x==y) return x; for(int i=20;i>=0;i--) if(f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i]; return f[x][0]; } signed main(){ scanf("%d",&n); iota(fa+1,fa+1+n+n,1),tot=n; for(int i=1;i<n;i++){ scanf("%d%d",&x,&y),x=find(x),y=find(y); fa[x]=fa[y]=++tot,val[tot]=i, v[tot].push_back(x),v[tot].push_back(y); } dep[tot]=1,dfs(tot); scanf("%d",&q); while(q--){ scanf("%d",&k),ans=1; for(int i=1;i<=k;i++) scanf("%d",&a[i]); sort(a+1,a+1+k,[](int x,int y){return dfn[x]<dfn[y];}); for(int i=1;i<=k;i++){ int mn=n-1; if(i>1) mn=val[lca(a[i],a[i-1])]-1; if(i<k) mn=min(mn,val[lca(a[i],a[i+1])]-1); ans=1ll*ans*(mn+1)%mod; } printf("%d\n",ans); } return 0; }
|