Cod sursa(job #2211430)

Utilizator AlexandruabcdeDobleaga Alexandru Alexandruabcde Data 10 iunie 2018 12:10:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>

using namespace std;

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

vector <int> G[100002];
queue <int> Q;

int n, m, S, x, y, lg[100002];

bool viz[100002];

void Bfs (int nod)
{
    vector <int> :: iterator it;
    viz[nod] = true;
    Q.push(nod);

    while (!Q.empty())
    {
        int x = Q.front();
        for (it = G[x].begin(); it != G[x].end(); it++)
        {
            if (!viz[*it])
            {
                Q.push(*it);
                viz[*it] = true;
                lg[*it] = lg[x] + 1;
            }
        }
        Q.pop();
    }
}
int main()
{
    f >> n >> m >> S;

    for (int i = 1; i <= m; i++)
    {
        f >> x >> y;
        G[x].push_back(y);
    }

    Bfs(S);

    for (int i = 1; i <= n; i++)
    {
        if (!viz[i]) g << "-1 ";
        else g << lg[i] << " ";
    }
    return 0;
}