【蓝桥杯】试题 历届真题 发现环【第八届】【决赛】【A组】

该程序采用深度优先搜索(DFS)来检测图中的环。通过保存路径和已访问过的节点,当再次访问到已访问节点时,找出环并存储在集合s中。最后输出环中的节点。地图结构由邻接集表示,每个节点可以到达其他节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用一个集合保存已经经过的点,path数组保存走过的路径,从一个点开始dfs,如果再次来到走过点就说明发现了环,此时去path中找到第一次出现这个点的位置,从这个点往后就是环中的元素了。

#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<math.h>
#include<set>
#include<string>
#include<stack>
using namespace std;
#include<queue>
#include<sstream>
//s集合用来存放环中的元素,也就是放答案的集合
set<int>s;
//map1是图结构,当前点-可达到的点。used保存经过的点,path保存经过的点的路径,cur当前节点,pre上一个节点
void dfs(map<int, set<int> >& map1, set<int>& used, vector<int>& path,int cur,int pre)
{
	//cout << cur<<" "<<pre << endl;
	if (s.size() != 0)
	{
		return;
	}
//再次来到一个经过了的点
	if (used.count(cur) == 1)
	{
		int begin = 0;
		for (int i = 0; i < path.size(); i++)
		{
			if (path[i] == cur)
			{
				begin = i;
				break;
			}
		}
		for (int i = begin; i < path.size(); i++)
		{
			s.insert(path[i]);
		}
		return;
	}
	set<int>::iterator it;
	for (it = map1[cur].begin(); it != map1[cur].end(); it++)
	{
//这里pre==(*it)是防止ABA这样的情况出现
		if ((*it) == pre)
		{
			continue;
		}
		used.insert(cur);
		path.push_back(cur);
		dfs(map1, used, path, (*it),cur);
		path.pop_back();
		used.erase(cur);
	}
}
int main()
{
	map<int, set<int> >map1;
	int n = 0;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		int a, b;
		cin >> a >> b;
		map1[a].insert(b);
		map1[b].insert(a);
	}
	set<int>used;
	vector<int>path;
	dfs(map1, used, path, 1,-1);
	set<int>::iterator it;
	for (it = s.begin(); it != s.end(); it++)
	{
		cout << (*it) << " ";
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值