Cod sursa(job #3371058)

Utilizator ioanaghisoiuGhiosiu Ioana-Diana ioanaghisoiu Data 28 octombrie 2026 13:40:36
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 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( )
{
    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();
        g<<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]++;
    }


    TopSort();

    return 0;
}