萌新求助简单图论题
  • 板块P4320 道路相遇
  • 楼主dk_qwq
  • 当前回复1
  • 已保存回复1
  • 发布时间2022/10/7 19:14
  • 上次更新2023/10/27 08:16:14
查看原帖
萌新求助简单图论题
311306
dk_qwq楼主2022/10/7 19:14

我不是btd

一直T掉#11-#14,不知道怎么改了/kk

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
inline int read(){
	int x=0;short p=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){
		if(ch=='-') p=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9'){
		x=(x<<3)+(x<<1)+(ch^48);
		ch=getchar();
	}
	return x*p;
}
const int N=5e5+5;
vector<int>g[N],adj[N<<1];
void add_adj(int u,int v){
	adj[u].push_back(v);
	adj[v].push_back(u);
}
void add_g(int u,int v){
	g[u].push_back(v);
	g[v].push_back(u);
}
int dfn[N],low[N],inde;
int cnt;
int st[N],tp;
void tarjan(int u){
	dfn[u]=low[u]=++inde;
	st[++tp]=u;
	for(auto v:g[u]){
		if(!dfn[v]){
			tarjan(v);
			low[u]=min(low[u],low[v]);
			if(low[v]>=dfn[u]){
				cnt++;
				add_adj(cnt,u);
				int x=0;
				do{
					x=st[tp--];
					add_adj(cnt,x);
				}while(x!=v);
			}
		}
		else low[u]=min(low[u],dfn[v]);
	}
}
int n,m,q;
int fa[N<<1],son[N<<1];
int siz[N<<1],dep[N<<1];
void dfs0(int u,int fno){
	fa[u]=fno;
	dep[u]=dep[fno]+1;
	siz[u]=1;
	for(auto v:adj[u]){
		if(v==fno) continue;
		dfs0(v,u);
		siz[v]+=siz[u];
		if(siz[v]>siz[son[u]]) son[u]=v;
	}
}
int top[N<<1];
void dfs1(int u,int f){
	top[u]=f;
	if(!son[u])	return ;
	dfs1(son[u],f);
	for(auto v:adj[u]){
		if(v==fa[u]||v==son[u]) continue;
		dfs1(v,v);
	}
}
int LCA(int u,int v){
	while(top[u]!=top[v]){
		if(dep[top[u]]<dep[top[v]]) swap(u,v);
		u=fa[top[u]];
	}
	return dep[u]<dep[v]?u:v;
}
int main() {
	n=read(),m=read();
	cnt=n;
	while(m--){
		int u=read(),v=read();
		add_g(u,v);
	}
	tarjan(1);
	dfs0(1,0),dfs1(1,1);
	q=read();
	while(q--){
		int u=read(),v=read();
		int lca=LCA(u,v);
		printf("%d\n",(dep[u]+dep[v]-2*dep[lca])/2+1);
	}
}
2022/10/7 19:14
加载中...