Cod sursa(job #2969494)

Utilizator Balauta_AlbertBalauta Albert Balauta_Albert Data 23 ianuarie 2023 11:44:56
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
#define N 100005
using namespace std;

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

vector<int> g[N];
int n, m, s;
int d[N];
queue<int> q;

void afis(){
    for(int i = 1; i <= n; ++i){
        cout << i << ' ';
        for(auto nod : g[i]){
            cout << nod << " ";
        }
        cout << '\n';
    }
}

void bfs(){
    q.push(s);
    while(!q.empty()){
        int i = q.front();
        q.pop();
        for(auto nod : g[i]){
            if(!d[nod] && nod != s){
                d[nod] = d[i] + 1;
                q.push(nod);
            }
        }
    }
}

int main() {

    fin >> n >> m >> s;
    for(int i = 0; i < m; ++i){
        int x, y;
        fin >> x >> y;
        if (x != y)
            g[x].push_back(y);
    }
    bfs();
    for(int i = 1; i <= n; ++i){
        if (d[i] == 0 && i != s)
            fout << -1 <<" ";
        else
            fout << d[i]<<" ";
    }
    return 0;
}