Cod sursa(job #2377373)

Utilizator dan.ghitaDan Ghita dan.ghita Data 10 martie 2019 06:07:49
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

int n, m, s, a, b;
vector< vector<int> > lv;
vector<int> dist;

void bfs(int s)
{
    deque<int> dq;

    dq.push_back(s);
    dist[s] = 0;

    while (!dq.empty())
    {
        int x = dq.front();
        dq.pop_front();

        for (auto next : lv[x])
            if (dist[next] == -1)
                dist[next] = dist[x] + 1,
                dq.push_back(next);
    }
}

int main()
{
    f >> n >> m >> s;

    lv.resize(n + 1);
    dist.resize(n + 1, -1);

    while (m--)
        f >> a >> b,
        lv[a].push_back(b);

    bfs(s);

    for (int i = 1; i < dist.size(); ++i)
        g << dist[i] << ' ';

    return 0;
}