Codeforces D. Fish Graph

注释十分详细

#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int N=2010;
vector<int> e[N],p;//path用来记录环路径
bool co[N],st[N];//co指的是与检验点直接相邻的点,st指的是已经走过的点

bool dfs(int now,int tfp)//tfp指的是与检验节点相邻的第一个点the_first_point
{
	if(st[now])	return false;//因为是无向图,走过的点不再走,达到不往回走的目的
	p.push_back(now);	//用来记录环路径
	st[now]=1;
	if(co[now]&&now!=tfp)	return true;
	//tfp的作用 跳过第一个与检验节点相邻的第一个点,
	//如果下次走到了另一个与检验点直接相邻的点且不是第一个与检验点直接相邻的点,那么必定成环有解。
	for(auto t:e[now])//否则继续深搜
		if(dfs(t,tfp))	return true;
	p.pop_back();//如果最后不是环 则回溯清空记录的path环路径
	return false;
}
int main(){IOS
	int t;cin>>t;
	while(t--){
		int n,m;cin>>n>>m;
		for(int i=1;i<=n;i++)	e[i].clear();
		while(m--){
			int x,y;cin>>x>>y;
			e[x].push_back(y);
			e[y].push_back(x);
		}int f=0;
		for(int i=1;i<=n;i++){	
			if(e[i].size()>=4){			//如果该节点度数>=4,检验其是否在一个环上,如果在则必定有解
				for(int i=1;i<=n;i++)	st[i]=0,co[i]=0;//初始化
				p.clear();st[i]=1;//检验点默认走过了
				for(auto t:e[i])		co[t]=1;//标记与检验点相邻的点
				for(auto t:e[i]){
					if(dfs(t,t)){//枚举与检验点相邻的点,如果某一条路径成环,则有解
						f=i;break;
					}
				}
			}
		}
		if(f){
			cout<<"YES"<<endl;
			int l=p.size();
			cout<<p.size()+3<<endl;
			cout<<f<<' '<<p[0]<<endl;
			cout<<f<<' '<<p[l-1]<<endl;
			for(int i=0;i<l-1;i++)	cout<<p[i]<<' '<<p[i+1]<<endl;
			int co=0;
			for(auto t:e[f]){
				if(co==2)	break;
				if(t!=p[0]&&t!=p[l-1]) cout<<f<<' '<<t<<endl,co++;
			}
		}else	cout<<"NO"<<endl;
	}
	return 0;
} 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值