Cod sursa(job #2660675)

Utilizator Harsa_AndreiHarsa Andrei Harsa_Andrei Data 20 octombrie 2020 08:31:37
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <bits/stdc++.h>

using namespace std;

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

list<int> M[100002];

int d[100002], n, m;

void BFS(int k)
{
    for(int i = 1; i <= n; i++)
        d[i] = -1;
    
    d[k] = 0;
    queue<int> Q;
    Q.push(k);

    while(!Q.empty())
    {
        int x = Q.front();
        Q.pop();
        for(int y : M[x])
            if(d[y] == -1)
            {
                d[y] = d[x] + 1;
                Q.push(y);
            }
    }
}

int main()
{
    int k, x, y;
    fin >> n >> m >> k;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        M[x].push_back(y);
    }
    BFS(k);
    for(int i = 1; i <= n; i++)
        fout << d[i] << ' ';
}