Cod sursa(job #2361755)

Utilizator ZheroAlexandru Culea Zhero Data 2 martie 2019 18:23:57
Problema Sortare topologica Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 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()
{
    short int x=1;
    unsigned short int k;
    short int sw=0;
    while(sw==0)
    {
        k=1;
        V[x]=1;
        S[1]=x;
        sw=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()]!=0)
                A[S[k]].pop_back();
            else
            {
                Q.push_back(S[k]);
                k--;
            }
        }
        for(int i=1;i<=N;i++)
            if(V[i]==0)
            {
                x=i;
                sw=0;
            }
    }
    while(!Q.empty())
    {
        g<<Q.back()<<" ";
        Q.pop_back();
    }
    g.close();
}
int main()
{
    citire();
    parcurgere();
    return 0;
}