Cod sursa(job #2602999)

Utilizator sichetpaulSichet Paul sichetpaul Data 18 aprilie 2020 13:36:12
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>
#define Nmax 50005
using namespace std;

ifstream f("sortaret.in");
ofstream g("sortaret.out");

int N, M;
bool in[Nmax], vis[Nmax];
vector<int> G[Nmax], ans;
queue<int> Q;

void BFS(int start) {
    Q.push(start);
    ans.push_back(start);
    vis[start] = 1;
    while (!Q.empty()) {
        int node = Q.front();
        Q.pop();
        for (auto it: G[node]) {
            if (vis[it]) continue;
            vis[it] = 1;
            Q.push(it);
            ans.push_back(it);
        }
    }
}
int main()
{
    f >> N >> M;
    while (M--) {
        int x, y;
        f >> x >> y;
        in[y] = 1;
        G[x].push_back(y);
    }

    for (int i = 1; i <= N; ++i)
       if (in[i] == 0) BFS(i);

    for (auto it: ans)
        g << it << " ";

    return 0;
}