Mai intai trebuie sa te autentifici.

Cod sursa(job #3165193)

Utilizator stefanrotaruRotaru Stefan-Florin stefanrotaru Data 5 noiembrie 2023 16:59:07
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

int n, m, st, cost[100005];

queue <int> q;

vector <int> a[100005];

void bfs()
{
    while(!q.empty()) {
        int nod = q.front();
        q.pop();

        for (auto vecin : a[nod]) {
            if(cost[vecin] == -1) {
                cost[vecin] = cost[nod] + 1;
                q.push(vecin);
            }
        }
    }
}

int main()
{
    f >> n >> m >> st;

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

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

    cost[st] = 0;

    q.push(st);

    bfs();

    for (int i = 1; i <= n; ++i) {
        g << cost[i] << ' ';
    }

    return 0;
}