Cod sursa(job #2711191)

Utilizator danhHarangus Dan danh Data 23 februarie 2021 19:07:51
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

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

const int inf = (1<<30) - 1;
const int NMAX = 1e5 + 1;

int dist[NMAX];

vector<int> v[NMAX];
bitset<NMAX> viz;
queue<int> q;

void BFS(int x)
{
    viz[x] = 1;
    q.push(x);
    dist[x] = 0;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        for(int el : v[x])
        {
            if(!viz[el])
            {
                dist[el] = dist[x] + 1;
                q.push(el);
                viz[el] = 1;
            }
        }
    }
}

int main()
{
    int n, m, s, x, y;

    fin>>n>>m>>s;

    for(int i=1; i<=m; i++)
    {
        fin>>x>>y;
        v[x].push_back(y);
    }

    for(int i=1; i<=n; i++)
    {
        dist[i] = inf;
    }

    BFS(s);

    for(int i=1; i<=n; i++)
    {
        if(dist[i] == inf)
            fout<<-1<<' ';
        else
            fout<<dist[i]<<' ';
    }

    return 0;
}