Cod sursa(job #3258069)

Utilizator AnduRazvanMindrescu Andu AnduRazvan Data 20 noiembrie 2024 19:02:41
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

long long n, m, k, cnt = 0,d[100003], x, y, viz[100001];

vector<int>g[100001];
queue<int>q;

int main()
{
    fin >> n >> m >> k;
    for(int i = 1; i <= n; i++)
        d[i] = -1;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        g[x].push_back(y);
    }
    q.push(k);
    d[k] = 0;
    viz[k] = 1;
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        for(int i = 0; i < g[nod].size(); i++)
        {
            if(viz[g[nod][i]] == 0)
            {
                d[g[nod][i]] = d[nod] + 1;
                q.push(g[nod][i]);
                viz[g[nod][i]] = 1;
            }
        }
    }
    for(int i = 1; i <= n; i++)
        fout << d[i] << " ";
    return 0;
}