Cod sursa(job #3248505)

Utilizator devilexeHosu George-Bogdan devilexe Data 12 octombrie 2024 09:22:53
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("sortaret.in");
ofstream fout("sortaret.out");
int N, M;
const int MAXN = 50000;
vector<int> G[MAXN + 1];
queue<int> Q;
int degree[MAXN + 1];
vector<int> sol;

int main()
{
    fin >> N >> M;
    int a, b;
    while (M--)
    {
        fin >> a >> b;
        G[a].push_back(b);
        degree[b]++;
    }
    for (int i = 1; i <= N; ++i)
        if (degree[i] == 0)
            Q.push(i);
    while (!Q.empty())
    {
        int n = Q.front();
        Q.pop();
        sol.push_back(n);
        for (const auto &x : G[n])
        {
            degree[x]--;
            if (degree[x] == 0)
                Q.push(x);
        }
    }
    for (const auto &x : sol)
        fout << x << ' ';
    return 0;
}