Cod sursa(job #2670065)

Utilizator robeert.77Chirica Robert robeert.77 Data 8 noiembrie 2020 20:58:58
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin ("sortaret.in");
ofstream fout ("sortaret.out");
vector<int> v[50001];
map<int, int> nodes;
int keyElement[50001];

void dfs(int currentNode) {
    fout << keyElement[currentNode] << " ";
    for (vector<int>::iterator it = v[currentNode].begin(); it != v[currentNode].end(); it++)
        dfs(*it);
}

void push_map(int a, int b, int &nr) {
    if (nodes.find(a) == nodes.end()) {
        nodes.insert(pair<int, int>(a, nr));
        keyElement[nr++] = a;
    }
    if (nodes.find(b) == nodes.end()) {
        nodes.insert(pair<int, int>(b, nr));
        keyElement[nr++] = b;
    }
}

int main() {
    fin.tie(0);
    ios::sync_with_stdio(0);
    int n, m;
    fin >> n >> m;
    bool inDegree[n + 1] = {0};
    int a, b, nr = 1;
    for (int i = 0; i < m; i++) {
        fin >> a >> b;
        push_map(a, b, nr);
        v[nodes[a]].push_back(nodes[b]);
        inDegree[nodes[b]] = true;
    }

    int startNode;
    for (int i = 1; i <= n; i++)
        if (!inDegree[i]) {
            startNode = i;
            break;
        }
    dfs(startNode);
    return 0;
}