Cod sursa(job #2792568)

Utilizator rexlcdTenea Mihai rexlcd Data 1 noiembrie 2021 22:09:26
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

vector < int > v[100002];
queue < int > q;
int d[100002];

int main()
{
    ifstream f("bfs.in");
    ofstream g("bfs.out");

    int n, m, s; f >> n >> m >> s;
    for(int i = 1; i <= m; i++)
    {
        int x, y; f >> x >> y;
        v[x].push_back(y);
    }
    memset(d, 0x3f3f3f3f, sizeof(d));

    q.push(s);
    d[s] = 0;
    while(!q.empty())
    {
        int x = q.front();
        q.pop();

        for(int neighbour: v[x])
            if(d[x] + 1 < d[neighbour])
            {
                d[neighbour] = d[x] + 1;
                q.push(neighbour);
            }
    }

    for(int i = 1; i <= n; i++)
        g << (d[i] == 0x3f3f3f3f ? -1 : d[i]) << ' ';
    g << '\n';
    f.close();
    g.close();
    return 0;
}