TLE 求助
查看原帖
TLE 求助
420129
Nt_Tsumiki楼主2023/3/18 07:55
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;
int n,cnt1,cnt2,dfncnt,top,N,T,m,q;
int head1[100001],head2[200001],dfn[200001],low[200001],s[100001],son[200001],tp[200001],fa[200001],siz[200001],vis[200001],dep[200001],a[201],len[200001],ed[200001];

struct Node { int to,nxt; }e1[200001],e2[400001];

void add1(int x,int y) { e1[++cnt1]=(Node){y,head1[x]},head1[x]=cnt1; }
void add2(int x,int y) { e2[++cnt2]=(Node){y,head2[x]},head2[x]=cnt2; }

void clear() {
	memset(head1,0,sizeof head1);
	memset(head2,0,sizeof head2);
	memset(dfn,0,sizeof dfn);
	memset(low,0,sizeof low);
	memset(son,0,sizeof son);
	cnt1=cnt2=dfncnt=top=0;
}

void tarjan(int x,int f) {
	dfn[x]=low[x]=++dfncnt,s[++top]=x;
	for (int i=head1[x];i;i=e1[i].nxt) {
		int y=e1[i].to;
		if (y==f) continue;
		if (!dfn[y]) {
			tarjan(y,x);
			low[x]=min(low[x],low[y]);
			if (low[y]>=dfn[x]) {
				add2(++N,x),add2(x,N);
				add2(N,y),add2(y,N);
				while (s[top]!=y) {
					add2(N,s[top]),add2(s[top],N);
					top--;
				} top--;
			}
		} else low[x]=min(low[x],dfn[y]);
	}
}

void dfs1(int x,int f) {
	dfn[x]=++dfncnt,siz[x]=(x<=n),fa[x]=f,len[x]=len[f]+(x<=n),dep[x]=dep[f]+1;
	for (int i=head2[x];i;i=e2[i].nxt) {
		int y=e2[i].to;
	 	if (y==f) continue;
	 	dfs1(y,x);
	 	if (siz[y]>siz[son[x]]) son[x]=y;
		siz[x]+=siz[y];
	}
	ed[x]=dfncnt;
}

void dfs2(int x,int topp) {
	tp[x]=topp;
	if (son[x]) dfs2(son[x],topp);
	for (int i=head2[x];i;i=e2[i].nxt) {
		int y=e2[i].to;
		if (y==fa[x] or y==son[x]) continue;
		dfs2(y,y);
	}
}

int LCA(int x,int y) {
	while (tp[x]!=tp[y]) {
		if (dep[tp[x]]<dep[tp[y]]) swap(x,y);
		x=fa[tp[x]];
	}
	if (dep[x]>dep[y]) swap(x,y);
	return x;
}

bool cmp(int x,int y) { return dfn[x]<dfn[y]; }

int main() {
	scanf("%d",&T);
	while (T--) {
		scanf("%d%d",&n,&m); N=n;
		clear();
		for (int i=1,x,y;i<=m;i++) {
			scanf("%d%d",&x,&y);
			add1(x,y),add1(y,x);
		}
		tarjan(1,0); dfncnt=0,len[1]=1;
		dfs1(1,0); dfs2(1,1);
		scanf("%d",&q);
		while (q--) {
			int S;
			scanf("%d",&S);
			for (int i=1;i<=S;i++) {
				scanf("%d",a+i);
				vis[a[i]]=1;
			}
			sort(a+1,a+S+1,cmp); int t1=S;
			for (int i=1;i<t1;i++) {
				int lca=LCA(a[i],a[i+1]);
				if (!vis[lca]) a[++S]=lca,vis[lca]=1;
			}
			sort(a+1,a+S+1,cmp);
			top=0,s[0]=fa[a[1]];
			int ans=0;
			for (int i=1;i<=S;i++) {
				while (top and !(dfn[s[top]]<dfn[a[i]] and ed[s[top]]>=ed[a[i]])) top--;
				ans+=len[a[i]]-len[s[top]];
				s[++top]=a[i],vis[a[i]]=0;
			}
			printf("%d\n",ans-t1);
		}
	}
	return 0;
}
/*
2 7 6 1 2 1 3 2 4 2 5 3 6 3 7 3 2 1 2 3 2 3 4 4 4 5 6 7 6 6 1 2 1 3 2 3 1 4 2 5 3 6 4 3 1 2 3 3 1 2 6 3 1 5 6 3 4 5 6
*/
2023/3/18 07:55
加载中...