Cod sursa(job #2919378)

Utilizator andreibrosPeta Andrei Mathias andreibros Data 17 august 2022 09:57:31
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream in("sortaret.in");
ofstream out("sortaret.out");
queue <int> coada;
vector <int> graf[50001];
int grad[50001];
int sortare_top[50001];
int main()
{
    int n,m,x,y;
    in>>n>>m;
    for(int i=1; i<=m; i++)
    {
        in>>x>>y;
        grad[y]++;
        graf[x].push_back(y);
    }
    for(int i=1; i<=n; i++)
        if(grad[i]==0)
            coada.push(i);
    int pos=0;
    while(!coada.empty())
    {
        x=coada.front();
        coada.pop();
        sortare_top[pos++]=x;
        for(int i=0 ;i<graf[x].size(); i++)
        {
            y=graf[x][i];
            grad[y]--;
            if(grad[y]==0)
                coada.push(y);
        }

    }
    for(int i=0; i<n; i++)
        out<<sortare_top[i]<<" ";
    return 0;
}