Cod sursa(job #3246522)

Utilizator antonio.grGrigorascu Andrei Antonio antonio.gr Data 3 octombrie 2024 15:38:27
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 1e5;
vector<int> L[NMAX + 1];
int dist[NMAX + 1];

void bfs(int source){
    dist[source] = 0;
    queue<int> q;

    q.push(source);

    while (!q.empty()){
        int node = q.front();
        q.pop();
        for(auto next: L[node]){
            if(dist[next] == -1){
                dist[next] = dist[node] + 1;
                q.push(next);
            }
        }

    }
}


int main() {
    int n, m, s;
    fin >> n >> m >> s;

    for(int i = 1; i < m; i++){
        int x, y;
        fin >> x >> y;
        L[x].push_back(y);
    }

    for(int i = 0; i < n; i++){
        dist[i] = -1;
    }

    bfs(s);

    for(int i = 1; i <= n; i++){
        fout << dist[i] << " ";
    }


    return 0;
}