Cod sursa(job #3352658)

Utilizator TonyyAntonie Danoiu Tonyy Data 30 aprilie 2026 09:54:20
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

const int nMax = 1e5 + 1;
int n, m, s;
vector<int> List[nMax], d(nMax, -1);
queue<int> q;

void bfs(int node) {
    q.push(node);
    d[node] = 0;
    while (!q.empty()) {
        node = q.front();
        q.pop();
        for (int i : List[node]) {
            if (d[i] == -1) {
                d[i] = d[node] + 1;
                q.push(i);
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);

    fin >> n >> m >> s;
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        List[x].push_back(y);
    }
    bfs(s);
    for (int i = 1; i <= n; i++) {
        fout << d[i] << " ";
    }

    fin.close();
    fout.close();
    return 0;
}