Cod sursa(job #2493298)

Utilizator GhSamuelGherasim Teodor-Samuel GhSamuel Data 16 noiembrie 2019 11:27:08
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>
#define Nmax 100005
using namespace std;

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

vector <int> G[Nmax];
queue <int> Coada;
int cost[Nmax], viz[Nmax];

void BFS(int node)
{
    for (vector <int>::iterator i = G[node].begin(); i != G[node].end(); ++i) {
        if (!viz[*i]) {
            viz[*i] = 1;
            cost[*i] = cost[node] + 1;
            Coada.push(*i);
        }
    }
    Coada.pop();
    if (!Coada.empty())
        BFS(Coada.front());
}

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

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

    for (int i = 1; i <= n; ++i)
        cost[i] = -1;

    cost[s] = 0;
    viz[s] = 1;
    Coada.push(s);
    BFS(s);

    for (int i = 1; i <= n; ++i)
        g << cost[i] << " ";
    return 0;
}