Cod sursa(job #2189193)

Utilizator RobertAndruscaAndrusca Robert RobertAndrusca Data 27 martie 2018 20:09:19
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>
using namespace std;
int n, X, m, viz[100020], niv[100020];
vector <int> L[100020];
void Citire()
{
    int x, y;
    ifstream in("bfs.in");
    in >> n >> m >> X;
    for(int i = 1; i <= m; i++)
    {
        in >> x >> y;
        L[x].push_back(y);
    }
    in.close();
}
void BFS(int k)
{
    queue <int> q;
    q.push(k);
    viz[k] = 1;
    while(!q.empty())
    {
        int j = q.front();
        q.pop();
        viz[j] = 1;
        for(auto i : L[j])
            if(!viz[i])
            {
                q.push(i);
                niv[i] = niv[j] + 1;
            }
    }
}
int main()
{
    Citire();
    ofstream out("bfs.out");
    BFS(X);
    for(int i = 1; i <= n; i++)
        if(viz[i])out << niv[i] << " ";
        else out << "-1 ";
    return 0;
}