Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <stack>
- using namespace std;
- int n, m;
- vector <int> g[100010];
- int color [100010];
- bool fl = false;
- stack <int> st1;
- stack <int> st2;
- void dfs (int v)
- {
- color[v] = 1;
- st1.push(v);
- for (int i = 0; i < g[v].size() ; i++)
- {
- if (fl) break;
- int u = g[v][i];
- if (color[u] == 0)
- {
- dfs(u);
- }
- else
- {
- if (color[u] == 1)
- {
- fl = true;
- int k = st1.top();
- st1.pop();
- st2.push(k);
- while (k != u)
- {
- k = st1.top();
- st1.pop();
- st2.push(k);
- }
- }
- }
- }
- color[v] = 2;
- if (!st1.empty())
- {
- st1.pop();
- }
- }
- int main()
- {
- cin >> n >> m;
- for (int i = 0; i < m; i++)
- {
- int a, b;
- cin >> a, b;
- g[a - 1].push_back(b - 1);
- }
- for (int i = 0; i < n; i++)
- {
- color[i] = 0;
- }
- for (int i = 0; i < n; i++)
- {
- if (fl) break;
- if (color[i] == 0)
- {
- dfs(i);
- }
- }
- if (!fl)
- {
- cout << "NO";
- }
- else
- {
- cout << "YES" << endl;
- while (!st2.empty())
- {
- cout << st2.top() << " ";
- st2.pop();
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement