-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathRound Trip I.cpp
60 lines (51 loc) · 1.13 KB
/
Round Trip I.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e5+1;
int N, M, a, b, p[maxN], ds[maxN];
vector<int> ans, G[maxN];
void dfs(int u){
for(int v : G[u]){
if(v != p[u]){
p[v] = u;
dfs(v);
}
}
}
int find(int u){
if(ds[u] < 0) return u;
ds[u] = find(ds[u]);
return ds[u];
}
bool merge(int u, int v){
u = find(u); v = find(v);
if(u == v) return false;
if(ds[u] < ds[v]) swap(u, v);
ds[v] += ds[u];
ds[u] = v;
return true;
}
int main(){
scanf("%d %d", &N, &M);
fill(ds+1, ds+N+1, -1);
for(int i = 0; i < M; i++){
scanf("%d %d", &a, &b);
if(!merge(a, b)){
dfs(a);
int u = b;
while(u != 0){
ans.push_back(u);
u = p[u];
}
int K = ans.size();
printf("%d\n", K+1);
for(int j = 0; j < K; j++)
printf("%d ", ans[j]);
printf("%d\n", b);
return 0;
} else {
G[a].push_back(b);
G[b].push_back(a);
}
}
printf("IMPOSSIBLE\n");
}