Cod sursa(job #2212534)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 14 iunie 2018 13:02:31
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>

using namespace std;

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

int N, M, i, x, y, S;

int Lg[100005], T[100005];

vector <int> G[100005];

int nod;

bool sel[100005];

void load ()
{
    f>>N>>M>>S;

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

queue <int> Q;

void bf (int x)
{
    int i;

    sel[x]=true;

    Q.push(x);

    Lg[x]=T[x]=0;

    while(!Q.empty())
    {
        nod=Q.front();

        for(i=0; i<G[nod].size(); i++)
        {
            y=G[nod][i];

            if(!sel[y])
            {
                Q.push(y);
                sel[y]=true;
                T[y]=nod;
                Lg[y]=Lg[nod]+1;
            }
        }

        Q.pop();
    }
}

int main()
{
    load();
    bf(S);

    for(int i=1; i<=N; i++)
    {
        if(Lg[i] || i==S)
            g<<Lg[i];

        else g<<-1;

        g<<' ';
    }

    g<<'\n';

    return 0;
}