2017.发现环(并查集水题)

blog最近没有更新因为在做并查集专题,按专题写题解,然后又要打省赛,(省三水过,题解还没时间写,现在又要准备蓝桥国赛)
  • 并查集模板,但是我死磕路径压缩时进行保存答案
  • 应该邻接表存图,然后在根节点不相同的地方,去dfs找成环的路上的点,
  • 回溯是最重要的,能够回溯说明没有找到,需要取消标记然后pop路上的点
#include <iostream>
#include <string.h>
#include <vector>
#include <algorithm>

using namespace std;

const int maxn = 1e5+10;
int n;
int pre[maxn];
vector<int> e[maxn];
vector<int> ans;
bool vis[maxn];

void init() {
	for (int i=1; i<maxn; i++) pre[i] = i; 
}
int find(int x) {
	if (x == pre[x]) return x;
	return pre[x] = find(pre[x]);
}
bool flag = 1;
void dfs(int cur,int endn) {
	if (cur == endn) {
		sort(ans.begin(),ans.end() );
		for (int i=0; i<ans.size(); i++) {
			printf("%d",ans[i]);
			if (i != ans.size()-1) printf(" ");
			flag = false;
		}
	}
	for (int i=0; i<e[cur].size(); i++) {
		int to = e[cur][i];
		if (!vis[to] && flag) {
			vis[to] = 1;
			ans.push_back(to);
			dfs(to,endn);
			vis[to] = 0;
			ans.pop_back();
		}
	}
}
int main() {
//	freopen("a.txt","r",stdin);
	cin >> n;
	int start,endn;
	init();
	for (int i=1; i<=n; i++) {
		int a,b;
		cin >> a >> b;

		e[a].push_back(b);
		e[b].push_back(a);

		int ra = find(a);
		int rb = find(b);
		if (ra != rb) {
			pre[ra] = rb; //合并
		}
		else {
			start = a;
			endn = b;
		}
	}
	vis[start] = 1;
	ans.push_back(start);
	dfs(start , endn);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值