跳到正文

题解

题解 P7025 [NWRRC2017] Grand Test

UMS2约 3 分钟
原文
文章信息与版本

文章信息

发布
2024年7月27日
收录
2026年10月1日
更新
2026年11月7日
篇幅
约 3 分钟
获赞
2
题目
P7025

版本

  1. v1当前

题目概述

对于一个有 nn 个点,mm 条边的无向图,找到两个点 SS 与 TT,存在三条完全不同的路径。

1≤∑n,∑m≤1×1051\le \sum n, \sum m \le 1\times 10^5。

思路

先考虑图为一颗树的情况,此时任意两点间只有一条路径。若存在一条额外的边 (u,v)(u,v),则除 u,vu,v 之外,处于环内的点对于其他点都有两条不相交的路径。而扩展到第二个环,即可得到第三条路径,所以,问题就转化为找到被同时处于两个环内的边。

由于一个图的 dfs 树除树边外不存在横叉边,只存在返祖边,所以可以只考虑两条额外的边均为返祖边的情况。

由于一个环可以由额外边确定,可使用边 (u,v)(u,v) 来指代环,其中 uu 为 vv 的祖先。若用 (u,v)(u,v) 指代祖先深度更小的环,(x,y)(x,y)指代深度更大的环,则不难发现三条路径分别是:

  1. xx -> yy -> lca(v,y)lca(v,y)。
  2. xx -> uu -> vv -> lca(v,y)lca(v,y)。
  3. xx -> lca(v,y)lca(v,y)。

这样就找到了符合条件的方案,可以在 dfs 时同时记录边的覆盖情况,发现合法方案后直接记录输出即可。

Code

这里只展示 dfs 过程和方案的输出。

C++
void gpath(int lu,int ru,int lv,int rv){
	int lca=glca(lu,ru);
	if(dep[lv]<dep[rv]){
		swap(lv,rv);
		swap(lu,ru);
	}
	
	t=0;
	int tp=lca;
	cout<<lv<<' '<<lca<<endl;

	while(tp!=lv){
		res[++t]=tp;
		tp=fa[tp];
	}
	res[++t]=tp;

	cout<<t<<' ';
	for(int i=t;i;i--)cout<<res[i]<<' ';
	cout<<endl;
	t=0;
	
	tp=lv;
	while(tp!=rv){
		res[++t]=tp;
		tp=fa[tp];
	}
	res[++t]=tp;
	tp=ru;
	while(tp!=lca){
		res[++t]=tp;
		tp=fa[tp];
	}
	res[++t]=tp;
	
	cout<<t<<' ';
	for(int i=1;i<=t;i++)cout<<res[i]<<' ';
	cout<<endl;
	t=0;
	
	tp=lu;
	while(tp!=lca){
		res[++t]=tp;
		tp=fa[tp];
	}
	res[++t]=tp;
	
	cout<<(t+1)<<' '<<lv<<' ';
	for(int i=1;i<=t;i++)cout<<res[i]<<' ';
	cout<<endl;
	ed=1;
}

void dfs(int u){
	if(ed)return;
	dep[u]=dep[fa[u]]+1;
	vis[u]=inst[u]=1;
	for(int i=h[u],v;i&&!ed;i=e[i].u){
		v=e[i].v;
		if(v==fa[u])continue;
		if(!vis[v]){//未记录的点
			fa[v]=u;
			dfs(v);
		}
		else if(inst[v]){//发现环
			for(int p=u;p!=v;p=fa[p]){
				if(covu[p]&&covv[p]){
					gpath(covu[p],u,covv[p],v);
					break;
				}
				covu[p]=u;//标记环的两端点
				covv[p]=v;
			}
		}
	}
	inst[u]=0;
}
原文
存档评论1 条抓取于