forked from mpfeifer1/Kattis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjumpingmonkey.cpp
111 lines (92 loc) · 2.12 KB
/
jumpingmonkey.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <bits/stdc++.h>
using namespace std;
int find(vector<int>& d, int a) {
if(d[a] < 0) return a;
return d[a] = find(d,d[a]);
}
void join(vector<int>& d, int a, int b) {
a = find(d,a);
b = find(d,b);
if(a == b) return;
d[a] = b;
}
int n, m;
bool bfs(int state, vector<vector<int>>& adj) {
queue<int> q;
q.push(state);
vector<bool> vis(1<<n,false);
vector<pair<int,int>> par(1<<n);
par[state] = {-1,-1};
vis[state] = true;
bool works = false;
while(!q.empty()) {
int curr = q.front();
q.pop();
if(curr == 0) {
works = true;
break;
}
// For each node, if we shoot it,
for(int i = 0; i < n; i++) {
int next = 0;
for(int j = 0; j < n; j++) {
if(i == j) continue;
if(curr & (1<<j)) {
for(auto k : adj[j]) {
next |= (1 << k);
}
}
}
if(!vis[next]) {
vis[next] = true;
par[next] = {curr,i};
q.push(next);
}
}
}
if(works) {
vector<int> path;
int curr = 0;
while(curr != state) {
path.push_back(par[curr].second);
curr = par[curr].first;
}
cout << path.size() << ": ";
for(int i = path.size()-1; i >= 0; i--) {
cout << path[i] << " ";
}
cout << endl;
}
return works;
}
void solve() {
vector<int> d(n,-1);
vector<vector<int>> adj(n);
bool works = true;
for(int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
if(find(d,u) == find(d,v)) {
works = false;
}
join(d,u,v);
adj[u].push_back(v);
adj[v].push_back(u);
}
if(!works) {
cout << "Impossible" << endl;
return;
}
if(!bfs((1<<n)-1,adj)) {
cout << "Impossible" << endl;
}
}
int main() {
while(true) {
cin >> n >> m;
if(n == 0 && m == 0) {
break;
}
solve();
}
}