【回溯搜索+并查集判环】 发现环

问题描述

  小明的实验室有N台电脑,编号1~N。原本这N台电脑之间有N-1条数据链接相连,恰好构成一个树形网络。在树形网络上,任意两台电脑之间有唯一的路径相连。


  不过在最近一次维护网络时,管理员误操作使得某两台电脑之间增加了一条数据链接,于是网络中出现了环路。环路上的电脑由于两两之间不再是只有一条路径,使得这些电脑上的数据传输出现了BUG。


  为了恢复正常传输。小明需要找到所有在环路上的电脑,你能帮助他吗?

输入格式

  第一行包含一个整数N。
  以下N行每行两个整数a和b,表示a和b之间有一条数据链接相连。


  对于30%的数据,1 <= N <= 1000
  对于100%的数据, 1 <= N <= 100000, 1 <= a, b <= N


  输入保证合法。

输出格式

  按从小到大的顺序输出在环路上的电脑的编号,中间由一个空格分隔。

样例输入

5
1 2
3 1
2 4
2 5
5 3

样例输出

1 2 3 5


输入的同时判环,只要成环,这两个点以及这条边一定在环中,记录一组就可以了,然后从起点搜到终点,记录路径即可


#include <iostream>
#include <cstring>
#include <iomanip>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <cstdio>
using namespace std;
#define inf 1e18
typedef long long ll;
typedef long double ld;
const ll maxn = 1e5+100;
const ll mod = 1e9+7;
const ld pi = acos(-1.0);

ll n,a,b,pre[maxn],be,en,biao,temp[maxn];
bool flag[maxn];

ll fi(ll x)
{
	return pre[x] == x? x: pre[x] = fi( pre[x] );
}

vector<ll>arr[maxn];

void dfs(ll now,ll num)
{
	//cout << now << " ";
	if(now == en)
	{
		
		temp[num] = be;
		num++;
		
		sort(temp,temp+num);
	
		for(ll i = 0; i < num; i++)
			cout << temp[i] << " ";
		cout << endl;
		exit(0);
	}
	
	for(ll i = 0; i < arr[now].size(); i++)
	{
		ll to = arr[now][i];
		
		if(flag[to] == 0)
		{
			flag[to] = 1;
			temp[num] = to;
			
			dfs(to,num+1);
			
			flag[to] = 0;
			
		}
		
	}
	return ;
}

int main()
{
    ios::sync_with_stdio(false);

	cin >> n;
	
	for(ll i = 1; i <= n; i++)
		pre[i] = i;
	
	for(ll i = 1; i <= n; i++)
	{
		
		cin >> a >> b;
		
		arr[a].push_back(b);
		arr[b].push_back(a);
		
		ll t1 = fi(a);
		ll t2 = fi(b);
		
		if(t1 == t2 && biao == 0) //记录一组点即可
		{
			be = a,en = b;
			biao = 1;
		}
		else
		{
			pre[t1] = t2;
		}
	}
	//cout << be << " " << en << endl;
    flag[be] = 1;
	dfs(be,0);
		
    return 0;
}

/*
6
1 2
2 4
4 6
2 5
5 3
3 1
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值