Cod sursa(job #1706863)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 23 mai 2016 17:23:23
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int maxn = 100005;

vector <int> g[maxn];
int deg[maxn], n, m;
vector <int> tsort;

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

    fin >> n >> m;
    while(m --) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        ++ deg[y];
    }
    queue <int> q;
    for(int i = 1; i <= n; ++ i)
        if(deg[i] == 0)
            q.push(i);
    while(!q.empty()) {
        int node = q.front();
        tsort.push_back(node);
        q.pop();
        for(auto it : g[node])
            if(-- deg[it] == 0)
                q.push(it);
    }
    for(auto it : tsort)
        fout << it << ' ';
}