Cod sursa(job #2437497)

Utilizator DariusDCDarius Capolna DariusDC Data 9 iulie 2019 17:34:58
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");

struct lista
{
    int value;
    lista* next;
};

lista* head = NULL;

bool viz[50001];

void addNode(lista* &head, int val)
{
    lista *p = new lista;
    p->value = val;
    p->next = head;

    head = p;
}

void afis()
{
    while (head != NULL)
    {
        fout << head->value << " ";
        head = head->next;
    }
}

int n, m;

vector <int> G[50001];

void dfs(int nod)
{
    viz[nod] = true;
    for (unsigned int i = 0; i < G[nod].size(); i++)
    {
        int vecin = G[nod][i];
        if (viz[vecin])
            continue;
        dfs(vecin);
    }
    addNode(head, nod);
}

int main()
{
    fin >> n >> m;
    while (m--)
    {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }
    for (int i = 1; i <= n; i++)
        if (!viz[i])
            dfs(i);
    afis();
    return 0;
}