Cod sursa(job #2553970)

Utilizator oldatlantianSerban Cercelescu oldatlantian Data 22 februarie 2020 13:59:35
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fi("bfs.in");
ofstream fo("bfs.out");

const int N = 1e5 + 5;

vector<int> ladist[N];
vector<int> g[N];
int dist[N];
bool f[N];

int n, m, src;

/*
 *  q.front();
    q.push();
    q.pop();
    q.size();
    q.empty()
*/

int main() {
    fi >> n >> m >> src;
    for (int a, b, i = 0; i < m; ++i) {
        fi >> a >> b;
        g[a].push_back(b);
    }

    ladist[0].push_back(src);
    f[src] = true;
    for (int d = 0; !ladist[d].empty(); ++d) {
        for (auto nod: ladist[d]) {
            for (auto ngh: g[nod]) if (!f[ngh]) {
                ladist[d + 1].push_back(ngh);
                dist[ngh] = dist[nod] + 1;
                f[ngh] = true;
            }
        }
    }
    
    for (int i = 1; i <= n; ++i) {
        if (f[i])
            fo << dist[i] << ' ';
        else
            fo << -1 << ' ' ;
    }
    fo << endl;


    return 0;
}