萌新刚学OI求助
查看原帖
萌新刚学OI求助
253433
XeRnHe楼主2021/1/9 10:19

RT,样例都过不了

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#define MAXN 10005
#define MAXM 100005
using namespace std;
int n,m,tmp,tmpT,dfsTime,dccCount,q;
int head[MAXN],headT[MAXN];
int pre[MAXN],low[MAXN];
int depth[MAXN],parents[MAXN][100],log2[MAXN];
bool vis[MAXN];
struct Edge{
	int u,v,next;
}edge[MAXM<<1],edgeT[MAXN<<1];
stack<int> s;
inline void addEdge(int u,int v){
	edge[++tmp].u=u;
	edge[tmp].v=v;
	edge[tmp].next=head[u];
	head[u]=tmp;
}
inline void addEdgeT(int u,int v){
	edgeT[++tmpT].u=u;
	edgeT[tmpT].v=v;
	edgeT[tmpT].next=headT[u];
	headT[u]=tmpT;
}
void tarjan(int u,int father){
	pre[u]=low[u]=++dfsTime;
	s.push(u);
	for(int i=head[u];i;i=edge[i].next){
		int v=edge[i].v;
		if(pre[v]==0){
			tarjan(v,u);
			low[u]=min(low[u],low[v]);
			if(low[v]>=pre[u]){
				dccCount++;
				while(true){
					int t=s.top();
					s.pop();
					addEdgeT(n+dccCount,t);
					addEdgeT(t,n+dccCount);
					if(v==t)
						break;
				}
				addEdge(n+dccCount,u);
				addEdge(u,n+dccCount);
			}
		}else if(v!=father)
			low[u]=min(low[u],pre[v]);	
	}
}
void dfs(int u,int father){
	depth[u]=depth[father]+1;
	vis[u]=1;
	parents[u][0]=father;
    for(int i=1;(1<<i)<=depth[u];i++)
        parents[u][i]=parents[parents[u][i-1]][i-1];
    for(int i=headT[u];i;i=edgeT[i].next)
    	if(edgeT[i].v!=father&&!vis[u])
    		dfs(edgeT[i].v,u);
}
int lca(int x,int y){
    if(depth[x]<depth[y])
        swap(x,y);
    while(depth[x]>depth[y])
        x=parents[x][log2[depth[x]-depth[y]]-1];
    if(x==y)
        return x;
    for(int i=log2[depth[x]]-1;i>=0;i--)
        if(parents[x][i]!=parents[y][i]){
            x=parents[x][i];
            y=parents[y][i];
        }
    return parents[x][0];
}
inline int ans(int x,int y){
	return (depth[x]+depth[y]-2*depth[lca(x,y)])/2+1;
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		int u,v;
		cin>>u>>v;
		addEdge(u,v);
		addEdge(v,u);
	}
	for(int i=1;i<=n;i++)
		if(pre[i]==0)
			tarjan(i,0);
	for(int i=1;i<=n+dccCount;i++)
		if(vis[i]==0)
			dfs(i,0);
	dfs(1,0);
	for(int i=1;i<=n;i++)
        log2[i]=log2[i-1]+((1<<log2[i-1])==i);
    cin>>q;
    while(q--){
    	int x,y;
    	cin>>x>>y;
    	int maxn=ans(edge[x<<1].u,edge[y<<1].u);
    	maxn=max(maxn,ans(edge[x<<1].u,edge[y<<1].v));
    	maxn=max(maxn,ans(edge[x<<1].v,edge[y<<1].u));
    	maxn=max(maxn,ans(edge[x<<1].v,edge[y<<1].v));
    	cout<<maxn<<endl;
    }
	return 0;
}
2021/1/9 10:19
加载中...