BZOJ 5329: [Sdoi2018]战略游戏
圆方树+虚树
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,ti,cnt,Cnt,top,last[100005],Last[200005],F[200005][19],dfn[200005],low[100005],ed[200005],sz[200005],stack[100005],Num,Dep[200005],A[200005];
struct node{
int to,next;
}e[400005],E[400005];
void add(int a,int b){
e[++cnt].to=b;
e[cnt].next=last[a];
last[a]=cnt;
}
void ADD(int a,int b){
E[++Cnt].to=b;
E[Cnt].next=Last[a];
Last[a]=Cnt;
}
void erase(){
top=ti=cnt=Cnt=0;
for (int i=1; i<=n; i++) last[i]=0;
for (int i=1; i<=Num; i++) Last[i]=0;
for (int i=1; i<=Num; i++) dfn[i]=low[i]=0;
for (int i=1; i<=Num; i++)
for (int j=0; j<=18; j++) F[i][j]=0;
}
void Tarjan(int x){
dfn[x]=low[x]=++ti;
stack[++top]=x;
for (int i=last[x]; i; i=e[i].next){
int V=e[i].to;
if (!dfn[V]){
Tarjan(V);
low[x]=min(low[x],low[V]);
if (low[V]>=dfn[x]){
int u=-1;
ADD(++Num,x),ADD(x,Num);
while (u!=V){
u=stack[top--];
ADD(Num,u),ADD(u,Num);
}
}
}
else low[x]=min(low[x],dfn[V]);
}
}
void Pre(int x,int fa,int dep){
Dep[x]=dep,F[x][0]=fa,sz[x]=sz[fa]+(x<=n);
dfn[x]=++ti;
for (int i=1; i<=18; i++) F[x][i]=F[F[x][i-1]][i-1];
for (int i=Last[x]; i; i=E[i].next){
int V=E[i].to;
if (V==fa) continue;
Pre(V,x,dep+1);
}
ed[x]=ti;
}
bool cmp(int a,int b){
return dfn[a]<dfn[b];
}
int check(int x,int y){
return dfn[y]>=dfn[x] && dfn[y]<=ed[x];
}
int lca(int x,int y){
if (Dep[x]<Dep[y]) swap(x,y);
for (int i=18; i>=0; i--) if (Dep[F[x][i]]>=Dep[y]) x=F[x][i];
if (x==y) return x;
for (int i=18; i>=0; i--) if (F[x][i]!=F[y][i]) x=F[x][i],y=F[y][i];
return F[x][0];
}
int main(){
int T;
scanf("%d",&T);
while (T--){
scanf("%d%d",&n,&m);
for (int i=1; i<=m; i++){
int x,y;
scanf("%d%d",&x,&y);
add(x,y);
add(y,x);
}
Num=n;
Tarjan(1);
for (int i=1; i<=n; i++) dfn[i]=0;
ti=0;
Pre(1,0,1);
int q;
scanf("%d",&q);
while (q--){
int N;
scanf("%d",&N);
for (int i=1; i<=N; i++) scanf("%d",&A[i]);
sort(A+1,A+N+1,cmp);
N=unique(A+1,A+N+1)-A-1;
long long ans=0;
for (int i=1; i<=N; i++) if (A[i]<=n) ans--;
int M=N;
for (int i=1; i<M; i++) A[++N]=lca(A[i],A[i+1]);
sort(A+1,A+N+1,cmp);
N=unique(A+1,A+N+1)-A-1;
int top=0;
stack[0]=F[A[1]][0];
for (int i=1; i<=N; i++){
while (top && !check(stack[top],A[i])) top--;
stack[++top]=A[i];
ans+=sz[stack[top]]-sz[stack[top-1]];
}
printf("%lld\n",ans);
}
erase();
}
return 0;
}

浙公网安备 33010602011771号