Cod sursa(job #3164165)

Utilizator TonyyAntonie Danoiu Tonyy Data 2 noiembrie 2023 12:12:02
Problema BFS - Parcurgere in latime Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>
#include <vector>
#include <queue>
#define Max 100000
using namespace std;

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

vector <int> graph[Max];
queue  <int> q;

int v[Max], n, m, s, x, y;

void bfs (int node)
{
    q.push(node);
    v[node] = 1;
    while (!q.empty())
    {
        node = q.front();
        q.pop();
        for (int i : graph[node])
            if (!v[i])
            {
                q.push(i);
                v[i] = v[node] + 1;
            }
    }
}

void read()
{
    fin >> n >> m >> s;
    for (int i = 1 ; i <= m ; ++i)
    {
        fin >> x >> y;
        graph[x].push_back(y);
    }
}

void Fout()
{
    for (int i = 1 ; i <= n ; ++i)
        if (v[i])
            fout << v[i] - 1 << " ";
        else
            fout << -1 << " ";
}

int main()
{
    read();
    bfs(s);
    Fout();

    fin.close();
    fout.close();
    return 0;
}