Cod sursa(job #2896832)

Utilizator mihnea.tTudor Mihnea mihnea.t Data 30 aprilie 2022 22:24:15
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

#define INF ((int)1e9)
#define NMAX ((int)5e4)

using namespace std;

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

struct node_info {
    int t_st, t_fn;
    int node;
};

int n, m;
vector<int> a[NMAX + 1];

void toposort(int node, vector<node_info> &times, int &t) {
    times[node].t_st = t++;
    for (int i = a[node].size() - 1; i >= 0; --i) {
        int next_node = a[node][i];
        if (times[next_node].t_st == 0) {
            toposort(next_node, times, t);
        }
    }

    times[node].t_fn = t++;
}

int main(void) {
    fin >> n >> m;
    for (int i = 0; i < n; ++i) {
        int src, dest;
        fin >> src >> dest;
        a[src].push_back(dest);
    }
    
    vector<node_info> times(n + 1);
    int t = 1;

    for (int i = 1; i <= n; ++i) {
        times[i].node = i;
        if (times[i].t_st == 0) {
            toposort(i, times, t);
        }
    }

    // Sort the nodes decreasing by t_fn
    sort(times.begin() + 1, times.end(), [](node_info &a, node_info &b) {
        return a.t_fn > b.t_fn;
    });

    for (int i = 1; i <= n; ++i) {
        fout << times[i].node << " ";
    }

    return 0;
}