Cod sursa(job #3213758)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 13 martie 2024 13:38:13
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
using pii = pair<int,int>;
ifstream cin("sortaret.in");
ofstream cout("sortaret.out");
const int nmax = 5e4+1;
vector <int> g[nmax];
int n , m , x , y , ind , top[nmax];
bool viz[nmax];
void tsort(int x)
{
    viz[x] = 1;
    for(auto it : g[x])
    {
        if(viz[it]) continue;
        tsort(it);
    }
    top[ind--] = x;
}
signed main()
{
    cin >> n >> m;
    for(int i = 1 ; i <= m ; ++i)
    {
        cin >> x >> y;
        g[x].push_back(y);
    }
    ind = n;
    for(int i = 1 ; i <= n ; i++)
    {
        if(!viz[i]) tsort(i);
    }
    for(int i = 1 ; i <= n ; ++i) cout << top[i] << ' ';
    return 0;
}