Cod sursa(job #2706737)

Utilizator rarestudurTudur Rares rarestudur Data 15 februarie 2021 18:31:54
Problema BFS - Parcurgere in latime Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

const int N=100001;
int d[N];
queue <int> q;
vector <int> a[N];

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

void bfs(int s)
{
    q.push(s);
    d[s] = 0;
    while(!q.empty())
    {
        //scot x din queue
        int x=q.front();
        q.pop();
        for(auto y:a[x])
        {
            if(d[y] == -1)
            {
                q.push(y);
                d[y] = 1 + d[x];
            }
        }
    }
}

int main()
{
    int n,m,s; // s=punct de pornire
    in >> n >> m >> s;
    for(int i=1; i <= m; i++)
    {
        int x,y;
        in >> x >> y;
        a[x].push_back(y);
    }
    for(int i=1; i <= n; i++)
    {
        d[i] = -1;
    }
    bfs(s);
    for(int i=1; i <= n; i++)
    {
        out << d[i] << " ";
    }
    return 0;
}