题目传送门 代码:
#include<bits/stdc++.h>
using namespace std;
#define MEM(a,b,start,end) for(int ii=start;ii<=end;ii++) a[ii]=b
#define AddEdge1(u,v) edge[tot].to=v,edge[tot].next=head[u],head[u]=tot++
#define AddEdge2(u,v,len) edge[tot].to=v,edge[tot].len=len,edge[tot].next=head[u],head[u]=tot++
const int maxn=100000+100;
struct Edge{
int to,next;
}edge[maxn<<1];
int head[maxn],tot;
int fa[maxn],son[maxn],tmpson[maxn],du[maxn],mi[maxn];
inline bool cmp(int a,int b){
return du[a]>du[b];
}
void DFS(int u,int d,int f){
fa[u]=f;du[u]=d;son[u]=0;
for(int i=head[u];i!=-1;i=edge[i].next){
Edge e=edge[i];
int v=e.to;
if(v==f) continue;
DFS(v,d+1,u);
son[u]++;
}
}
int main(){
int T,C=0;
scanf("%d",&T);
while(T--){
int n,q;
scanf("%d%d",&n,&q);
MEM(head,-1,1,n);
tot=0;
for(int i=1;i<n;i++){
int u,v;
scanf("%d%d",&u,&v);
AddEdge1(u,v);
AddEdge1(v,u);
}
DFS(1,1,-1);
printf("Case #%d:\n",++C);
while(q--){
int m;
scanf("%d",&m);
for(int i=1;i<=m;i++){
scanf("%d",&mi[i]);
tmpson[mi[i]]=son[mi[i]];
}
sort(mi+1,mi+1+m,cmp);
int cnt=n-m;
for(int i=1;i<=m;i++){
if(tmpson[mi[i]]>=2) cnt++;
else if(tmpson[mi[i]]==0 && mi[i]!=1) tmpson[fa[mi[i]]]--;
}
printf("%d\n",cnt);
}
}
}