Cod sursa(job #2862697)

Utilizator Madalin_IonutFocsa Ionut-Madalin Madalin_Ionut Data 5 martie 2022 18:44:44
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m, s;
vector<int> L[100003];
int d[100003];
bitset<100003> viz;

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

void BFS(int k)
{
    int x, i;
    for (i = 1; i <= n; i++)
        d[i] = 2e9;
    queue<int> q;
    d[k] = 0;
    q.push(k);
    while (!q.empty())
    {
        x = q.front();
        q.pop();
        if (!viz[x])
        {
            viz[x] = 1;
            for(int f : L[x])
                if (d[f] > d[x] + 1)
                {
                    d[f] = d[x] + 1;
                    q.push(f);
                }
        }
    }
}

void Afisare()
{
    int i;
    for (i = 1; i <= n; i++)
        if (d[i] == 2e9) fout << "-1 ";
        else fout << d[i] << " ";
}

int main()
{
    Citire();
    BFS(s);
    Afisare();
}