Cod sursa(job #3166348)

Utilizator AlexInfoIordachioaiei Alex AlexInfo Data 8 noiembrie 2023 16:53:15
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>

using namespace std;

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

typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
#define fi first
#define se second

#define NMAX 100005
#define MOD 1999999973
#define INF 0x3f3f3f3f

int n, m;
bool visited[NMAX];
vector<vector<int>> graf(NMAX);
vector<int> top;

void read()
{
    int x, y;
    in >> n >> m;
    for (int i = 1; i <= m; i++)
        in >> x >> y, graf[x].push_back(y);
}

void BFS(int start)
{
    queue<int> Q;
    Q.push(start);
    visited[start] = 1;

    while (!Q.empty())
    {
        int node = Q.front();
        Q.pop();
        top.push_back(node);

        for (auto e : graf[node])
            if (!visited[e])
                visited[e] = 1, Q.push(e);
    }
}

void solve()
{
    BFS(1);
    for (auto e : top)
        out << e << ' ';
}

int main()
{
    read();
    solve();
    return 0;
}