历届试题 发现环
程序员文章站
2022-05-21 11:49:29
...
//蠢到自己了.....
//n懒得传参...然鹅,我在main函数里,,将他自减为0了...调了好久,,还有就是表及问题...刚开始未进dfs时标记,dfs开头第一个判断是否拜访过,拜访过,则考虑邻接表下一个值....导致遇到环了 ,但是被标记,无法进入输出循环里........然后 改了下标记顺序,在递归前标记......递归后去掉标记
#include<iostream>
#include<cstdio>
#include<vector>
#include<cstring>
using namespace std;
const int N = 100000+5;
vector<int> V[2*N];
int parent[N], S, E, n;
int vis[N] = {0};
void init()
{
for(int i=0; i<=N; i++){
parent[i] = i;
}
}
int Find(int a)
{
return parent[a] == a? a : (parent[a] = Find(parent[a]));
}
bool Union(int a, int b)
{
// cout << a << " par " << b << endl;
a = Find(a);
b = Find(b);
if(a == b){//已构成环
return true;
}
else {
parent[a] = b;
return false;
}
}
void dfs(int u)
{
// cout << u << E <<endl;
if(u == E){//到达终点
// cout<< n << "输出结果为:" ;
for(int i=1; i<=n; i++){
// cout << i << ":" << vis[i] << endl;
if(vis[i]){
cout << i;
printf((i == n) ? "\n" : " ");
//cout << ((i==n) ? endl : " ");
}
}
return;
}
// else cout << u << "!=" << E << endl;
for(int i=0; i<V[u].size(); i++){
int next = V[u][i];
if(vis[next] == 0){
vis[next] = 1;
dfs(next);
vis[next] = 0;
}
}
return;
}
int main()
{
cin >> n;
init();
for(int i=0; i<n; i++){
int u, v;
cin >> u >> v;
// cout << u << " init " << v << endl;
if(Union(u, v)){//已构成环
S = u, E = v;
break;
}
else {
V[u].push_back(v);
V[v].push_back(u);
}
}
// cout << "start:" << S << " end:" << E << endl;
vis[S] = 1;
dfs(S);
return 0;
}