Cod sursa(job #2187428)

Utilizator Andrei17Andrei Pascu Andrei17 Data 26 martie 2018 15:18:57
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.73 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int N = 50002;

int n, m, pred[N];
vector <int> a[N], q;

void citire() {
    in >> n >> m;

    int x, y;
    for (int i = 0; i < m; i++) {
        in >> x >> y;
        pred[y]++;
        a[x].push_back(y);
    }

    for (int i = 1; i <= n; i++) {
        if (pred[i] == 0) q.push_back(i);
    }

    in.close();
}

int main()
{
    citire();

    int x, y, st = 0;
    while (st < q.size()) {
        x = q[st++];
        out << x << ' ';

        for (int i = 0; i < a[x].size(); i++) {
            y = a[x][i];
            pred[y]--;

            if (pred[y] == 0) q.push_back(y);
        }
    }

    out.close();
}