Cod sursa(job #2444359)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 31 iulie 2019 12:47:38
Problema BFS - Parcurgere in latime Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <bits/stdc++.h>

using namespace std;

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

vector <int> a[100000];
queue <int> q;
int d[100005];

void bfs(int k)
{
    d[k] = 0;
    q.push(k);
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        for(auto v : a[x])
            if(!d[v] && v != k) d[v] = d[x] + 1, q.push(v);
    }
}
int main()
{
    ios::sync_with_stdio(false);
    fin.tie(0);
    int n, m, s;
    fin >> n >> m >> s;
    for(int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        a[x].push_back(y);
    }
    bfs(s);
    for(int i = 1; i < s; ++i) fout << (d[i] == 0 ? -1 : d[i]) << " ";
    fout << "0" << " ";
    for(int i = s + 1; i <= n; ++i) fout << (d[i] == 0 ? -1 : d[i]) << " ";
    return 0;
}