QOJ.ac

QOJ

IDSubmission IDProblemHackerOwnerResultSubmit timeJudge time
#408#110526#6543. Visiting FriendCrysflyCrysflyFailed.2023-10-14 16:19:112023-10-14 16:19:11

Details

Extra Test:

Accepted
time: 99ms
memory: 117232kb

input:

1
200000 210000
46726 9636
161459 96589
99460 193854
63907 57719
157703 91326
117844 99044
110544 9361
91951 178097
63802 164574
38775 4491
122567 136537
196013 40330
114917 49420
73353 153314
174756 136537
51366 70204
188161 32879
154165 52796
123431 193001
44587 191828
16 84199
195100 40136
183852...

output:


result:

ok 0 number(s): ""

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#110526#6543. Visiting FriendCrysflyAC ✓622ms143380kbC++171.9kb2023-06-02 18:22:362023-06-02 18:22:39

answer

#include<bits/stdc++.h>
#define For(i,a,b) for(int i=(a);i<=(b);++i)
#define Rep(i,a,b) for(int i=(a);i>=(b);--i)
using namespace std;
inline int read()
{
	char c=getchar();int x=0;bool f=0;
	for(;!isdigit(c);c=getchar())f^=!(c^45);
	for(;isdigit(c);c=getchar())x=(x<<1)+(x<<3)+(c^48);
	if(f)x=-x;return x;
}

#define fi first
#define se second
#define pb push_back
#define mkp make_pair
typedef pair<int,int>pii;
typedef vector<int>vi;

#define maxn 1000005
#define inf 0x3f3f3f3f

int n,m,cnt;

vi e[maxn],g[maxn];
int dfn[maxn],low[maxn],bel[maxn],idx,fa[maxn][20];
int stk[maxn],tp;
void tar(int u,int pa)
{
	dfn[u]=low[u]=++idx,stk[++tp]=u;
	for(auto v:e[u]){
		if(v==pa)continue;
		if(!dfn[v]){
			tar(v,u);
			low[u]=min(low[u],low[v]);
			if(low[v]>=dfn[u]){
				++cnt; int x; 
				g[u].pb(cnt); fa[cnt][0]=u;
				do{
					x=stk[tp--];
					g[cnt].pb(x),bel[x]=cnt; //cout<<"addg "<<cnt<<" "<<x<<endl;
					fa[x][0]=cnt;
				}while(x!=v);
			}
		}
		else low[u]=min(low[u],dfn[v]);
	}
}

int sz[maxn],dep[maxn];
int L[maxn],R[maxn],qwq;
void dfs(int u,int pa){
	sz[u]=(u<=n);
	L[u]=++qwq; dep[u]=dep[pa]+1;
	For(i,1,19) fa[u][i]=fa[fa[u][i-1]][i-1];
	for(int v:g[u])if(v!=pa)dfs(v,u),sz[u]+=sz[v];
	R[u]=qwq;
}

int kth(int u,int k){
	For(i,0,19)if(k>>i&1)u=fa[u][i];
	return u;
}
int jump(int u,int v){return kth(u,dep[u]-dep[v]-1);}

void work()
{
	n=read(),m=read(),cnt=n;idx=0;
	For(i,1,n*2){
		e[i].clear(),g[i].clear();
		dfn[i]=low[i]=bel[i]=sz[i]=0;
	}
	For(i,1,m){
		int u=read(),v=read();
		e[u].pb(v),e[v].pb(u);
	}
	tar(1,0);
	qwq=0;
	dfs(1,0);
	int q=read();
	while(q--){
		int res=0,u=read(),v=read();
		if(L[u]>L[v])swap(u,v);
		if(L[u]<=L[v] && R[u]>=R[v]){
			int w=jump(v,u);
			res=sz[w]-sz[v]+2;
		}else{
			res=n-sz[u]-sz[v]+2;
		}
		printf("%d\n",res);
	}
}

signed main()
{
	int T=read();
	while(T--)work();
	return 0;
}