Cod sursa(job #3335249)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 22 ianuarie 2026 05:00:10
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;
using graph = vector<vector<int>>;

namespace InParser
{
    static constexpr int BSIZE = (1 << 16);
    char buff[BSIZE];

    int pos = (BSIZE - 1);

    char get_char()
    {
        ++pos;

        if (pos == BSIZE)
        {
            int n = fread(buff, 1, BSIZE, stdin);
            if (n != BSIZE)
                for (int i = n; i < BSIZE; ++i)
                    buff[i] = 0;

            pos = 0;
        }

        return buff[pos];
    }

    int get_int()
    {
        int answer = 0;

        for (;;)
        {
            char ch = get_char();
            if (ch >= '0' && ch <= '9')
            {
                answer = (int)(ch - '0');
                break;
            }
        }

        for (;;)
        {
            char ch = get_char();
            if (ch >= '0' && ch <= '9')
                answer = answer * 10 + (int)(ch - '0');
            else
                break;
        }

        return answer;
    }
};

void add_edge(graph &G)
{
    int x = InParser ::get_int(), y = InParser ::get_int();
    G[x].push_back(y);

    return;
}

void dfs(const int node, const graph &G, vector<bool> &used, vector<int> &v)
{
    used[node] = true;
    for (const int &adj : G[node])
        if (!used[adj])
            dfs(adj, G, used, v);

    v.push_back(node);
}

int main()
{
    freopen("sortaret.in", "r", stdin);
    freopen("sortaret.out", "w", stdout);

    ios_base ::sync_with_stdio(false);
    cin.tie(nullptr);

    int n = InParser ::get_int(), m = InParser ::get_int();
    graph G(n + 1);
    for (int i = 1; i <= m; ++i)
        add_edge(G);

    vector<bool> used((n + 1), false);
    vector<int> v = {};

    for (int i = 1; i <= n; ++i)
        if (!used[i])
            dfs(i, G, used, v);

    reverse(v.begin(), v.end());

    for (int i = 0; i < n; ++i)
    {
        printf("%d", v[i]);

        if (i == (n - 1))
            printf("\n");
        else
            printf(" ");
    }

    return 0;
}