这题的解法有两种
解法1:拓扑排序法,一个环里的点的度都是2,通过拓扑排序把所有能遍历到的点都遍历了,最后没有遍历的点的度数都为2,就是答案。
#include <bits/stdc++.h>
#define x first
#define y second
#define mem(h) memset(h,-1,sizeof h)
#define mcp(a,b) memcpy(a,b,sizeof b)
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
typedef pair< int , int > PII;
typedef pair< double , double > PDD;
namespace IO{
inline LL read ( ) {
LL o= 0 , f= 1 ; char c= getchar ( ) ;
while ( c< '0' || c> '9' ) { if ( c== '-' ) f= - 1 ; c= getchar ( ) ; }
while ( c>= '0' && c<= '9' ) { o= o* 10 + c- '0' ; c= getchar ( ) ; }
return o* f;
}
} using namespace IO;
const int N= 1e5 + 7 , M= 2e5 + 7 , INF= 0x3f3f3f3f , mod= 1e8 + 7 , P= 131 ;
int h[ N] , e[ M] , ne[ M] , idx;
int d[ N] ;
bool st[ N] ;
int n;
void add ( int a, int b) {
e[ idx] = b, ne[ idx] = h[ a] , h[ a] = idx++ ;
}
void topo ( ) {
queue< int > q;
for ( int i= 1 ; i<= n; i++ ) {
if ( d[ i] == 1 ) {
q. push ( i) ;
st[ i] = 1 ;
}
}
while ( ! q. empty ( ) ) {
int u= q. front ( ) ; q. pop ( ) ;
for ( int i= h[ u] ; ~ i; i= ne[ i] ) {
int j= e[ i] ;
if ( st[ j] ) continue ;
if ( -- d[ j] == 1 ) {
q. push ( j) ;
st[ j] = 1 ;
}
}
}
}
int main ( ) {
mem ( h) ;
cin>> n;
for ( int a, b, i= 0 ; i< n; i++ ) {
cin>> a>> b;
add ( a, b) , add ( b, a) ;
d[ a] ++ , d[ b] ++ ;
}
topo ( ) ;
for ( int i= 1 ; i<= n; i++ ) {
if ( ! st[ i] ) cout<< i<< " " ;
}
return 0 ;
}
解法2:并查集+dfs,首先在两个点建边时判断是否已经在一个集合,如果是则这是一个环。就以一个点为起始点搜索到最终点即可。
#include <bits/stdc++.h>
#define x first
#define y second
#define mem(h) memset(h,-1,sizeof h)
#define mcp(a,b) memcpy(a,b,sizeof b)
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
typedef pair< int , int > PII;
typedef pair< double , double > PDD;
namespace IO{
inline LL read ( ) {
LL o= 0 , f= 1 ; char c= getchar ( ) ;
while ( c< '0' || c> '9' ) { if ( c== '-' ) f= - 1 ; c= getchar ( ) ; }
while ( c>= '0' && c<= '9' ) { o= o* 10 + c- '0' ; c= getchar ( ) ; }
return o* f;
}
} using namespace IO;
const int N= 1e5 + 7 , M= 2e5 + 7 , INF= 0x3f3f3f3f , mod= 1e8 + 7 , P= 131 ;
int h[ N] , e[ M] , ne[ M] , idx;
int ans[ N] ;
bool st[ N] ;
int fa[ N] ;
int n;
int sx, ex;
void add ( int a, int b) {
e[ idx] = b, ne[ idx] = h[ a] , h[ a] = idx++ ;
}
int find ( int x) {
return x== fa[ x] ? x: fa[ x] = find ( fa[ x] ) ;
}
void dfs ( int x, int cnt) {
ans[ cnt] = x;
if ( x== ex) {
sort ( ans, ans+ cnt+ 1 ) ;
for ( int i= 0 ; i<= cnt; i++ ) {
cout<< ans[ i] << " " ;
}
cout<< endl;
return ;
}
st[ x] = 1 ;
for ( int i= h[ x] ; ~ i; i= ne[ i] ) {
int j= e[ i] ;
if ( st[ j] ) continue ;
dfs ( j, cnt+ 1 ) ;
}
st[ x] = 0 ;
}
int main ( ) {
mem ( h) ;
cin>> n;
for ( int i= 0 ; i<= n; i++ ) fa[ i] = i;
int a, b;
for ( int i= 0 ; i< n; i++ ) {
cin>> a>> b;
if ( find ( a) != find ( b) ) {
fa[ find ( a) ] = find ( b) ;
add ( a, b) , add ( b, a) ;
} else {
sx= a, ex= b;
}
}
dfs ( sx, 0 ) ;
return 0 ;
}