Cod sursa(job #3283522)

Utilizator Tudor_EnacheEnache Tudor Tudor_Enache Data 9 martie 2025 18:53:35
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

vector<int>vecini[200005];
const int INF = 100001;
vector<int>distanta(200005, INF);

void bfs(int n, int start){
    distanta[start] = 0;
    queue<int> q;
    vector<bool>vizitat(n+1, false);
    q.push(start);
    while(!q.empty()){
        int nodCurent = q.front();
        q.pop();
        for(auto nodNou : vecini[nodCurent]){
            if(distanta[nodNou] > distanta[nodCurent] + 1){
                distanta[nodNou] = distanta[nodCurent] + 1;
                q.push(nodNou);
            }
        }

    }

}

int main(){
    int n,m,s;
    cin >> n >> m >>s;
    for(int i =0; i < m;i++){
        int x,y;
        cin >> x >> y;  
        vecini[x].push_back(y);
    }
    bfs(n, s);
    for(int i = 1; i <= n; i++){
        if(distanta[i] == INF){
            cout << -1 << " ";
        }else{
            cout << distanta[i] << " ";
        }
    }
}