Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #define push_back pb
- #include <string>
- #include <vector>
- #include <iostream>
- using namespace std;
- vector<int> g[100005];
- int parent[100005];
- int visited[100005];
- vector<int> path;
- vector<int> a;
- int cycle, cycle_begin, cycle_end;
- void dfs(int s) {
- visited[s] = 1;
- for (int i=0; i < g[s].size(); i++) {
- if (visited[g[s][i]] == 0) { parent[g[s][i]] = s; dfs(g[s][i]); }
- else if (visited[g[s][i]] == 1) { cycle = 1; cycle_begin = g[s][i]; cycle_end = s; }
- }
- visited[s] = 2;
- }
- int main() {
- int n, m;
- cin >> n >> m;
- for (int i=0; i<m; i++) {
- int a, b;
- cin >> a >> b;
- g[a].pb(b);
- }
- for (int i=1; i < n+1; i++) {
- if (cycle == 1) { break; }
- if (visited[i] == 0) { dfs(i); }
- }
- if (cycle == 1) {
- cout << "YES" << endl;
- while (cycle_end != cycle_begin) {
- a.pb(cycle_end);
- cycle_end = parent[cycle_end];
- }
- a.pb(cycle_begin);
- reverse(a.begin(), a.end());
- for (int i=0; i < a.size(); i++) {
- cout << a[i] << " ";
- }
- }
- else {
- cout << "NO" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment