Cod sursa(job #2341569)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 11 februarie 2019 22:51:36
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>
#define inf (1 << 30)
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

vector <int> L[100005];
queue <int> q;

int n, m, S, d[100005];

void Citire()
{
    int i, x, y;
    fin >> n >> m >> S;
    for(i = 1; i <= m; i++)
    {
        fin >> x>> y;
        L[x].push_back(y);
    }
}

void BFS()
{
    int el, nod;
    d[S] = 0;
    q.push(S);
    while(!q.empty())
    {
        el = q.front();
        q.pop();

        for(int i = 0; i < L[el].size(); i++)
        {
            nod = L[el][i];
            if(d[nod] > d[el] + 1)
            {
                d[nod] = d[el] + 1;
                q.push(nod);
            }
        }
    }
}


int main()
{
    int i;
    Citire();
    for(i = 1; i <= n; i++)
        d[i] = inf;

    BFS();

    for(i = 1; i <= n; i++)
        if(d[i] != inf)
            fout << d[i] << " ";
        else fout << "-1 ";
    return 0;
}