Cod sursa(job #3235369)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 17 iunie 2024 14:30:47
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <bits/stdc++.h>

std :: ifstream in ("bfs.in");

std :: ofstream out ("bfs.out");

const int NMAX = 1e5 + 5;

int n;

int m;

int start;

int x;

int y;

std :: vector <int> v[NMAX];

std :: queue <int> q;

int cost[NMAX];

void bfs()
{
    while(!q.empty())
    {
        int nod = q.front();

        q.pop();

        for(int i : v[nod])
        {
            if(cost[i] == 0)
            {
                cost[i] = cost[nod] + 1;

                q.push(i);
            }
        }
    }
}

int main()
{

    in >> n >> m >> start;

    for(int i = 1; i <= m; i ++)
    {
        in >> x >> y;

        v[x].push_back(y);
    }

    q.push(start);

    cost[start] = 1;

    bfs();

    for(int i = 1; i <= n; i ++)
    {
        out << cost[i] - 1 << " ";
    }

    return 0;
}