Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- int main() {
- ios_base::sync_with_stdio(false);
- cin.tie(NULL);
- int N, M;
- cin >> N >> M;
- vector<vector<int> > adj(N + 1);
- vector<int> in_degree(N + 1, 0);
- for (int i = 0; i < M; i++) {
- int u, v;
- cin >> u >> v;
- adj[u].push_back(v);
- in_degree[v]++;
- }
- queue<int> q;
- for (int u = 1; u <= N; u++) {
- if (in_degree[u] == 0) {
- q.push(u);
- }
- }
- vector<int> topo_order;
- while (!q.empty()) {
- int u = q.front();
- q.pop();
- topo_order.push_back(u);
- for (int v : adj[u]) {
- in_degree[v]--;
- if (in_degree[v] == 0) {
- q.push(v);
- }
- }
- }
- if (topo_order.size() == N) {
- for (int u : topo_order) {
- cout << u << ' ';
- }
- cout << endl;
- } else {
- cout << -1 << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement