Cod sursa(job #2820748)

Utilizator sanzianagrecuSanziana Grecu sanzianagrecu Data 21 decembrie 2021 13:41:19
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>

using namespace std;

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

#define NMAX 100001

int n, m, src;

vector <int> adia[NMAX];

int vizitat[NMAX], distanta[NMAX];

void Bfs() {
    vizitat[src] = 1;
    distanta[src] = 0;

    queue <int> q;
    q.push(src);
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        for (auto i : adia[x]) {
            if (!vizitat[i]) {
                vizitat[i] = 1;
                q.push(i);
                distanta[i] = distanta[x] + 1;
            }
        }
    }
}

int main()
{
    fin >> n >> m >> src;
    for (int i = 1; i <= m; ++ i) {
        int a, b;
        fin >> a >> b;
        adia[a].push_back(b);
    }

    Bfs();

    for (int i = 1; i <= n; ++ i) {
        if (!vizitat[i])
            fout << -1 << ' ';
        else
            fout << distanta[i] << ' ';
    }

    return 0;
}