Cod sursa(job #3214349)

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

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

const int MAX_SIZE = 5 * 1e4;

void depthFirstSearch(int start, vector<int>& topologicalSorted, vector<vector<int>>& graph, vector<int>& inArches, vector<bool>& visited) {
    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);
                }
            }
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    vector<vector<int>> graph(MAX_SIZE + 1);
    vector<int> inArches(MAX_SIZE + 1, 0);
    vector<bool> visited(MAX_SIZE + 1, false);
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
        ++inArches[y];
    }
    int start;
    for (int i = 1; i <= n; ++i) {
        if (inArches[i] == 0) {
            start = i;
            break;
        }
    }
    vector<int> topologicalSorted;
    depthFirstSearch(start, topologicalSorted, graph, inArches, visited);
    for (int node : topologicalSorted) {
        fout << node << " ";
    }
    return 0;
}