Cod sursa(job #2831841)

Utilizator AlinaFloreaFlorea Alina AlinaFlorea Data 12 ianuarie 2022 11:45:29
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, p, d[100005];
bool viz[100005];
vector <int> edges[1000005];
queue <int> q;

void bfs(int x){
    q.push(x);
    viz[x] = 1;
    while(!q.empty()){
        int nod = q.front();
        q.pop();
        for(auto k : edges[nod])
            if(viz[k] == 0){
                viz[k] = 1;
                d[k] = d[nod] + 1;
                q.push(k);
            }
    }
}
int main()
{
    f >> n >> m >> p;
    int x, y;
    while(m--){
        f >> x >> y;
        edges[x].push_back(y);
    }
    bfs(p);
    for(int i = 1; i <= n; i++){
        if(d[i] == 0){
            if(i != p)
                g << "-1" << " ";
            else
                g << "0 ";
        }
        else
            g << d[i] << " ";
    }
    return 0;
}