Cod sursa(job #3142996)

Utilizator vozian.anghelinaAnghelina Vozian vozian.anghelina Data 26 iulie 2023 17:29:32
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
using namespace std;

int n,m,x,y,s, V[100100], C[100100], N[100100];
vector<int> G[100100];

int main(){
    ifstream cin("bfs.in");
    ofstream cout("bfs.out");
    cin >> n >> m >> s;
    for(int i=1; i<=m; i++){
        cin >> x >> y;
        G[x].push_back(y);
    }

    int l=0, r=0, op=0, e=0, s1=s;
    C[0] = s;
    V[s] = 1;
    while(l<=r){
        s = C[l++];
        op++;
        e = 0;
        for(int i=0; i<G[s].size(); i++){
            if(V[G[s][i]] != 1){
                C[++r] = G[s][i];
                V[G[s][i]] = 1; 
                N[G[s][i]] = op;
                // cout << op << ' ' << G[s][i] << endl;
                e = 1;
            }
        }
        if(!e){
            op--;
        }
    }

    for(int i=1; i<=n; i++){
        if(N[i] > 0){
            cout << N[i] << ' ';
        } else if(i == s1){
            cout << 0 << ' ';
        } else {
            cout << -1 << ' ';
        }
    }
}