Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <list>
- #include <queue>
- #include <cstring>
- #define ll long long
- #define ps push_back
- using namespace std;
- const int maxn = 1e5 + 10;
- vector<int> graph[maxn];
- bool visited[maxn];
- vector<int> cycle;
- bool dfs(int node, int parent) {
- visited[node] = true;
- for(int i = 0; i < (int) graph[node].size(); i++) {
- int neighbour = graph[node][i];
- cycle.push_back(neighbour);
- if(!visited[neighbour]) {
- if(dfs(neighbour, node)) {
- return true;
- }
- }
- else if(neighbour != parent) {
- return true;
- }
- cycle.pop_back();
- }
- return false;
- }
- int main() {
- int n,m;
- cin >>n >> m;
- for(int i = 0;i<m;i++){
- int a, b;
- cin >> a >> b;
- graph[a].push_back(b);
- graph[b].push_back(a);
- }
- memset(visited, false, sizeof visited);
- for(int i = 1; i <= n; i++) {
- cycle.push_back(i);
- if(!visited[i] and dfs(i, -1)) {
- vector<int> res;
- for(int j = (int) cycle.size() - 1; j >= 0; j--) {
- res.push_back(cycle[j]);
- if(cycle[j] == cycle[(int) cycle.size() - 1] and j != (int) cycle.size() - 1 ) {
- break;
- }
- }
- cout << res.size() << endl;
- for(int x : res) {
- cout << x << " " ;
- }
- return 0;
- }
- cycle.pop_back();
- }
- cout << "IMPOSSIBLE" << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement