My level is limited and I am only for learning. If you find any mistakes, thank you for pointing out
Topic link: Portal (click me)
Idea: First use the union check set to judge whether there is a ring, because the title is very clear, at first there are only N-1 lines, and now there is one more line to form a ring, then first use the union check set to judge, once it is found to be a ring, put that One of the two points is the starting point and the other is the end point, because the two are adjacent to each other. It is the edges that join the two computers that form the ring.
Storage: Here we use the adjacency list to store the edge (dynamic array implementation)
Search: It should be noted that since the computer not on the ring may also have an edge with the computer on the ring, the step of the DFS function is necessary here , because if you start Even if a computer outside the ring is searched , this path will be rolled back until it is overwritten by the computer number on the ring .
AC code:
#include<bits/stdc++.h>
using namespace std;
#define MAXN 100050
int p[MAXN],vis[MAXN],ans[MAXN];//parent visited answer
int n,a,b;
int s,en;//dfs (start end)
vector<int>e[MAXN];//edge
int f(int x){
return p[x]==-1?x:p[x]=f(p[x]);}//find root and compressed path
void pr(int step)
{
sort(ans+1,ans+1+step);
for(int i=1;i<=step;i++)cout<<ans[i]<<" ";
}
void dfs(int x,int step)
{
vis[x]=1;//sign
ans[step]=x;
if(x==en){
pr(step);return;}
for(int i=0;i<e[x].size();i++)
if(!vis[e[x][i]])dfs(e[x][i],step+1);
}
int main()
{
memset(p,-1,sizeof(p));//initialization
cin>>n;
while(n--){
cin>>a>>b;
if(f(a)==f(b))s=a,en=b;
else {
p[f(a)]=b;//merge
e[a].push_back(b);//edge
e[b].push_back(a);
}
}
dfs(s,1);
return 0;
}