Cod sursa(job #3142393)

Utilizator AlexPlesescuAlexPlesescu AlexPlesescu Data 21 iulie 2023 09:06:33
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>
#include <vector>
#include <queue>
#define pb push_back
#define NMAX 50005

using namespace std;

ifstream cin("sortaret.in");
ofstream cout("sortaret.out");

vector<int> adj[NMAX];
queue<int> Q;
int n,m,lista[NMAX],l;
bool vis[NMAX],fr[NMAX];
void bfs(int nod)
{
    Q.push(nod);
    vis[nod] = 1;
    while(!Q.empty())
    {
        cout << Q.front() << ' ';
        for(int k=0; k < adj[Q.front()].size(); k++)
        {
            if(!vis[adj[Q.front()][k]])
            {
                vis[adj[Q.front()][k]] = 1;
                Q.push(adj[Q.front()][k]);
            }
        }
        Q.pop();
    }
}
int main()
{
    cin >> n >> m;
    for(int i=1; i <= m; i++)
    {
        int x,y;
        cin >> x >> y;
        adj[x].pb(y);
        fr[y] = 1;
    }
    for(int i=1; i <= n; i++)
    {
        if(!fr[i])
        {
            bfs(i);
            break;
        }
    }
    return 0;
}