Cod sursa(job #2362090)

Utilizator ZheroAlexandru Culea Zhero Data 2 martie 2019 21:52:18
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

#define NMax 50002
ifstream f("sortaret.in");
ofstream g("sortaret.out");
vector <unsigned short int> A[NMax],Q;
unsigned short int N,V[NMax];
int M;
void citire()
{
    unsigned short int x,y;
    f>>N>>M;
    for(int i=1;i<=M;i++)
    {
        f>>x>>y;
        A[x].push_back(y);
    }
}
void Check(int x)
{
    while(!A[x].empty())
    {
        Check(A[x].back());
        A[x].pop_back();
    }
    if(V[x]==0)
    {
        Q.push_back(x);
        V[x]=1;
    }
}
void solutie()
{
    for(unsigned short int i=1;i<=N;i++)
    {
        if(A[i].empty() && V[i]==0)
        {
            Q.push_back(i);
            V[i]=1;
        }
        else
        {
            while(!A[i].empty())
            {
                Check(A[i].back());
                A[i].pop_back();
            }
            if(V[i]==0)
            {
                Q.push_back(i);
                V[i]=1;
            }
        }
    }
}
int main()
{
    citire();
    solutie();
    while(!Q.empty())
    {
        g<<Q.back()<<" ";
        Q.pop_back();
    }
    return 0;
}