Cod sursa(job #3246513)

Utilizator mihaidanaila11Danaila Mihai Teodor mihaidanaila11 Data 3 octombrie 2024 15:21:03
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 1e5;

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

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

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

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

    for(int i=0; i < m; i++){
        int x,y;
        in >> x >> y;
        L[x].push_back(y);
    }
    for(int i=1; i<=n; i++){
        dist[i] = -1;
    }
    bfs(s);
    for(int i=1; i<=n; i++){
        out << dist[i] << " ";
    }

    return 0;
}