直接上虚树dp一下就好了。。。
#include <bits/stdc++.h>
using namespace std;
#define N 1100000
#define ll long long
int n,Q,cnt,top,tot,m,tim;
int head[N],nex[N<<1],to[N<<1],st[N];
int a[N],pos[N],fa[N][21],deep[N],bj[N];
int f[N],size[N],g[N],a_mx,a_mn;
ll a_sum;
vector<int>ch[N];
void add(int x,int y)
{
tot++;
nex[tot]=head[x];head[x]=tot;
to[tot]=y;
}
void dfs(int x,int y)
{
pos[x]=++cnt;fa[x][0]=y;
deep[x]=deep[y]+1;
for(int i=1;i<=20;i++)
fa[x][i]=fa[fa[x][i-1]][i-1];
for(int i=head[x];i;i=nex[i])
if(to[i]!=y)
dfs(to[i],x);
}
int cmp(int x,int y){return pos[x]<pos[y];}
int lca(int x,int y)
{
if(deep[x]<deep[y])swap(x,y);
for(int i=20;i>=0;i--)
if(deep[fa[x][i]]>=deep[y])
x=fa[x][i];
if(x==y)return x;
for(int i=20;i>=0;i--)
if(fa[x][i]!=fa[y][i])
x=fa[x][i],y=fa[y][i];
return fa[x][0];
}
void dfs(int x)
{
f[x]=-n-1;size[x]=0;g[x]=n+1;
if(bj[x]==tim)g[x]=0,size[x]=1,f[x]=0;
for(int i=0,t;i<ch[x].size();i++)
{
dfs(t=ch[x][i]);
size[x]+=size[t];
int t1=g[t]+deep[t]-deep[x],t2=f[t]+deep[t]-deep[x];
a_mn=min(a_mn,g[x]+t1);
a_mx=max(a_mx,f[x]+t2);
g[x]=min(g[x],t1);f[x]=max(f[x],t2);
a_sum+=(ll)size[t]*(m-size[t])*(deep[t]-deep[x]);
}
}
int main()
{
//freopen("tt.in","r",stdin);
scanf("%d",&n);
for(int i=1,x,y;i<n;i++)
{
scanf("%d%d",&x,&y);
add(x,y);add(y,x);
}
dfs(1,0);
scanf("%d",&Q);
for(;Q--;)
{
scanf("%d",&m);tim++;
for(int i=1;i<=m;i++)
scanf("%d",&a[i]),bj[a[i]]=tim;
sort(a+1,a+1+m,cmp);
st[top=1]=1;ch[1].clear();
for(int i=1;i<=m;i++)
{
int t;
while((t=lca(st[top],a[i]))!=st[top])
{
if(deep[t]>deep[st[top-1]])
{
ch[t].clear();
ch[t].push_back(st[top]);
st[top]=t;
}
else ch[st[top-1]].push_back(st[top]),top--;
}
if(st[top]!=a[i])
ch[a[i]].clear(),st[++top]=a[i];
}
for(int i=top;i>1;i--)
ch[st[i-1]].push_back(st[i]);
a_mx=0;a_mn=n+1;a_sum=0;
dfs(1);
printf("%lld %d %d\n",a_sum,a_mn,a_mx);
}
return 0;
}