Cod sursa(job #2793256)

Utilizator francescom_481francesco martinut francescom_481 Data 3 noiembrie 2021 13:04:35
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");
#define cin fin
#define cout fout

#define N 100005
vector < vector < int > > g;
int n, m, s, x, y, d[N];

void fa(int nod)
{
    queue < int > q;
    q.push(nod);
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        for(int i = 0 ; i < g[x].size() ; i++)
        {
            if(d[g[x][i]] == -1)
            {
                d[g[x][i]] = d[x]+1;
                q.push(g[x][i]);
            }
        }
    }
}

int main()
{
    cin >> n >> m >> s;
    g.resize(n+5);
    for(int i = 1 ; i <= m ; i++)
    {
        cin >> x >> y;
        g[x].push_back(y);
    }
    for(int i = 1 ; i <= n ; i++)
    {
        d[i] = -1;
    }
    d[s] = 0;
    fa(s);
    for(int i = 1 ; i <= n ; i++)
    {
        cout << d[i] << " ";
    }
    return 0;
}