Cod sursa(job #2421955)

Utilizator viftode4Iftode Vlad viftode4 Data 16 mai 2019 19:49:22
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin( "sortaret.in" );
ofstream fout( "sortaret.out" );
int grad[50005];
int n, m, x, y;
vector <int> g[50005];
queue<int> q;
vector<int> sol;
int main()
{
    fin >> n >> m;

    for( int i = 1; i <= m; i++ )
        {
            fin >> x >> y;
            g[x].push_back( y );
            grad[y]++;
        }

    for( int i = 1; i <= n; i++ )
        if( !grad[i] )
            {
                q.push( i );
                sol.push_back( i );
            }


    while( !q.empty() )
        {
            int x = q.front();
            q.pop();


            for( auto it : g[x] )
                {
                    grad[it]--;

                    if( grad[it] == 0 )
                        {
                            q.push( it );
                            sol.push_back( it );
                        }

                }
        }

    for( auto it : sol )
        fout << it << ' ';

    return 0;
}