蓝桥杯 PREV-49 发现环(链表)

题目链接:

PREV-49 发现环

思路:

1.我们可以采用依次去掉度数为1的点的方法来寻找图中的环;
2.遍历的过程中可以采用链表方式,以减少时间开销;

代码:

#include<bits/stdc++.h>

using namespace std;

const int maxn = 1e6 + 5;
int n, nex[maxn], deg[maxn];
vector<int> G[maxn];

inline bool traverse() {
	bool flag = false;
	for(int p = 0, q = nex[0]; q; q = nex[q]) {
		if(deg[q] == 1) {
			nex[p] = nex[q];
			for(int i = 0; i < G[q].size(); i++) --deg[G[q][i]];
			flag = true;	
		}else p = q;
	}
	return flag;
}

int main() {
#ifdef MyTest
	freopen("Sakura.txt", "r", stdin);	
#endif
	scanf("%d", &n);
	for(int i = 0; i < n; i++) {
		int u, v;
		scanf("%d %d", &u, &v);	
		G[u].push_back(v), G[v].push_back(u);
		++deg[u], ++deg[v];
	}
	for(int i = 0; i < n; i++) nex[i] = i + 1;
	while(traverse());
	set<int> ans;
	for(int i = nex[0]; i; i = nex[i]) ans.insert(i);
	for(set<int> ::iterator it = ans.begin(); it != ans.end(); it++) 
		printf("%d ", *it);
	return 0;
}
发布了356 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_45228537/article/details/104411538