Cod sursa(job #3371066)

Utilizator valexandreiValeanu Alexandru-Andrei valexandrei Data 28 octombrie 2026 13:44:26
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("sortaret.in");
ofstream g("sortaret.out");
int n, m;
vector<int> in_deg;
vector<vector<int>> graph;
void TopSort(vector<int> &ans)
{
    queue<int> q;
    for (int i = 1; i <= n; i++)
        if (in_deg[i] == 0)
            q.push(i);

    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        ans.push_back(node);

        for (int neighbour : graph[node])
        {
            in_deg[neighbour]--;
            if (in_deg[neighbour] == 0)
                q.push(neighbour);
        }
    }
}
int main()
{
    f >> n >> m;
    in_deg.resize(n + 1);
    graph.resize(n + 1);

    for (int i = 1; i <= m; i++)
    {
        int x, y;
        f >> x >> y;
        graph[x].push_back(y);
        in_deg[y]++;
    }

    vector<int> ans;
    TopSort(ans);
    for (int node : ans)
        g << node << ' ';
    return 0;
}