Cod sursa(job #2756105)

Utilizator filicriFilip Crisan filicri Data 29 mai 2021 18:51:16
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <fstream>
#include <vector>
#include <queue>
#define N_MAX 100001

using namespace std;

int main() {
    int n, m, startingPoint;
    vector<int> G[N_MAX];
    ifstream f("bfs.in");
    f >> n >> m >> startingPoint;
    for (int i = 0; i < m; i++) {
        int x, y;
        f >> x >> y;
        G[x].push_back(y);
    }
    f.close();

    int dist[n + 1];
    for (int i = 1; i <= n; i++)
        dist[i] = INT_MAX;
    dist[startingPoint] = 0;
    queue<int> q;
    q.push(startingPoint);
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        for (const auto& ne: G[node])
            if (ne != startingPoint && dist[ne] > dist[node] + 1) {
                dist[ne] = dist[node] + 1;
                q.push(ne);
            }
    }

    ofstream g("bfs.out");
    for (int i = 1; i <= n; i++)
        g << (dist[i] == INT_MAX ? -1 : dist[i]) << ' ';
    g.close();
    return 0;
}