Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <map>
- #include <algorithm>
- using namespace std;
- using ll = long long;
- int cycle_start = -1, cycle_end;
- bool dfs(int v, const vector<vector<int>> &a, vector<int> &used, map<int, int>& p) {
- used[v] = 1;
- for (auto to : a[v]) {
- if (used[to] == 0) {
- p[to] = v;
- if (dfs(to, a, used, p)) {
- return true;
- }
- } else if (used[to] == 1) {
- cycle_start = v;
- cycle_end = to;
- return true;
- }
- }
- used[v] = 2;
- return false;
- }
- int main() {
- int n, m;
- cin >> n >> m;
- int u, v;
- vector<vector<int>> a(n);
- for (int to = 0; to < m; ++to) {
- cin >> v >> u;
- a[u - 1].push_back(v - 1);
- }
- vector<int> used(n);
- map<int, int> p;
- vector<int> f;
- for (int to = 0; to < n; ++to) {
- if(dfs(to, a, used, p)) {
- break;
- }
- }
- if (cycle_start == -1) {
- std::cout << -1;
- return 0;
- }
- vector<int> cycle;
- cycle.push_back (cycle_start);
- for (int v=cycle_end; v!=cycle_start && v.co; v=p[v]) {
- cycle.push_back (v);
- std::cout << v << "\n";
- }
- cycle.push_back (cycle_start);
- reverse (cycle.begin(), cycle.end());
- std::cout << cycle.size() << "\n";
- for (auto v: cycle) {
- std::cout << v << " ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement