Cod sursa(job #2104022)

Utilizator inquisitorAnders inquisitor Data 11 ianuarie 2018 00:43:02
Problema Sortare topologica Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>

using namespace std;

int vertices, edges, u, v;

vector<int> adj[50001], sortedList;

bool visited[50001];

void DFS(int start)
{
    stack<int> s; s.push(start);

    while(!s.empty())
    {
        int current = s.top(); s.pop();

        if(visited[current] == false)
        {
            sortedList.push_back(current);

            for(int child : adj[current])
            {
                s.push(child);
            }

            visited[current] = true;
        }
    }
}

int main()
{
    freopen("sortaret.in", "r", stdin);
    freopen("sortaret.out", "w", stdout);

    scanf("%d %d", &vertices, &edges);

    for(int i = 1; i <= edges; i++)
    {
        scanf("%d %d", &u, &v);

        adj[u].push_back(v);
    }

    DFS(1);

    for(int node : sortedList)
    {
        printf("%d ", node);
    }

    return 0;
}