Cod sursa(job #2361692)

Utilizator ZheroAlexandru Culea Zhero Data 2 martie 2019 17:59:43
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

#define NMax 50004

ifstream f("sortaret.in");
ofstream g("sortaret.out");

vector <unsigned short int> Q;
vector <unsigned short int> A[NMax];
int M;
unsigned short int N,V[NMax],S[NMax];
void citire()
{
    f>>N>>M;
    unsigned short int x,y;
    for(int i=1;i<=N;i++)
            V[i]=0;
    for(int i=1;i<=M;i++)
    {
        f>>x>>y;
        A[x].push_back(y);
    }
    f.close();
}
void parcurgere()
{
    V[1]=1;
    S[1]=1;
    unsigned short int k=1;
    while(k>0)
    {
        if(!A[S[k]].empty() && V[A[S[k]].back()]==0)
        {
            k++;
            S[k]=A[S[k-1]].back();
            V[S[k]]++;
            A[S[k-1]].pop_back();
        }
        else if(!A[S[k]].empty() && V[A[S[k]].back()]==1)
            A[S[k]].pop_back();
        else
        {
            Q.push_back(S[k]);
            k--;
        }
    }
    while(!Q.empty())
    {
        g<<Q.back()<<" ";
        Q.pop_back();
    }
    g.close();
}
int main()
{
    citire();
    parcurgere();
    return 0;
}