Cod sursa(job #3156006)

Utilizator Yanis3PiquePopescu Pavel-Yanis Yanis3Pique Data 10 octombrie 2023 13:34:03
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

int main() {
    const int NMAX = 100000;
    int N, M, S;
    f >> N >> M >> S;
    vector <int> G[N + 1];
    int vis[NMAX + 1] = {0};
    int d[NMAX + 1] = {-1};
    for(int i = 1; i <= M; i++) {
        int x, y;
        f >> x >> y;
        G[x].push_back(y);
    }

    queue<int> q;
    q.push(S);
    d[S] = 0;
    vis[S] = 1;
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        for (auto next : G[x]) {
            if (vis[next] == 0) {
                q.push(next);
                vis[next] = 1;
                d[next] = d[x] + 1;
            }
        }
    }

    for(int i = 1; i <= N; i++) {
        if(d[i] == 0 && i != S) d[i] = -1;
        g << d[i] << " ";
    }
}