Cod sursa(job #2193744)

Utilizator AlexandruabcdeDobleaga Alexandru Alexandruabcde Data 11 aprilie 2018 12:21:13
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f ("bfs.in");
ofstream g ("bfs.out");
bool a[100001];
int n,m,S,i,x,y,lg[100001];
vector <int> G[100001];
queue <int> Q;
void bfs (int nod)
{
    vector <int> :: iterator it;
    a[nod] = true;
    lg[nod] = 0;
    Q.push(nod);
    while (!Q.empty())
    {
        x = Q.front();
        for (it = G[x].begin(); it != G[x].end(); it++)
        {
            if (!a[*it])
            {
                Q.push(*it);
                a[*it] = true;
                lg[*it] = lg[x] + 1;
            }
        }
        Q.pop();
    }
}
int main()
{
    f >> n >> m >> S;
    for (i = 1; i <= m; i++)
    {
        f >> x >> y;
        G[x].push_back(y);
    }
    bfs(S);
    for (i = 1; i <= n; i++)
    {
        if (!a[i]) g << -1 << " ";
        else g << lg[i] << " ";
    }
    return 0;
}