Cod sursa(job #3213822)

Utilizator SilviuC25Silviu Chisalita SilviuC25 Data 13 martie 2024 14:58:37
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAX_SIZE = 5 * 1e4;
int n, m;
vector<int> graph[MAX_SIZE + 1];

void depthFirstSearch(int start) {
    vector<bool> visited(MAX_SIZE + 1, false);
    vector<int> topologicalSorted;
    stack<int> nodes;
    nodes.push(start);
    while (!nodes.empty()) {
        int currentNode = nodes.top();
        nodes.pop();
        if (!visited[currentNode]) {
            visited[currentNode] = true;
            topologicalSorted.push_back(currentNode);
            for (int neighbor : graph[currentNode]) {
                if (!visited[neighbor]) {
                    nodes.push(neighbor);
                }
            }
        }
    }
    for (int node : topologicalSorted) {
        fout << node << " ";
    }
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
    }
    depthFirstSearch(1);
    return 0;
}