Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int MAXN = 1e5 + 1;
- vector <int> g[MAXN], ans;
- short col[MAXN]; // 0 - unvisited, 1 - processing, 2 - visited
- bool dfs(int v) // Поиск в глубину (false - Ok, true - цикл)
- {
- col[v] = 1;
- for(int to : g[v])
- {
- if(col[to] == 1 or (col[to] == 0 and dfs(to)))
- return true;
- }
- col[v] = 2;
- ans.push_back(v);
- return false;
- }
- void topological_sort(int n)
- {
- for(int i = 1; i <= n; i++)
- if(col[i] == 0 and dfs(i))
- {
- ans.clear();
- return;
- }
- reverse(ans.begin(), ans.end());
- }
- int main()
- {
- // Ускорение ввода
- ios_base::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- // Ввод/вывод из файла
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- // Ввод
- int n, m;
- cin >> n >> m;
- while(m--)
- {
- int a, b;
- cin >> a >> b;
- g[a].push_back(b);
- }
- topological_sort(n); // Топологическая сортировка
- // Вывод
- if(ans.empty())
- cout << -1;
- else
- {
- for(int i : ans)
- cout << i << ' ';
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement