Cod sursa(job #3249201)

Utilizator PetstebPopa Petru Petsteb Data 15 octombrie 2024 13:41:46
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
// BFS orietated graph
// https://infoarena.ro/problema/bfs

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int NMAX = 1e5 + 5;
const int MMAX = 1e6 + 5;
int n, m, s;
int len[NMAX];

vector<vector<int>> gp(NMAX);

void BFS(int source)
{
    queue<int> q;
    q.push(source);
    len[source] = 0;
    while (!q.empty())
    {
        int node = q.front();
        q.pop();
        for (auto it : gp[node])
        {
            if (len[node] + 1 < len[it] || len[it] == 0)
            {
                len[it] = len[node] + 1;
                q.push(it);
            }
        }
    }
    for (int i = 1; i <= n; i++)
        if (len[i] == 0)
            len[i] = -1;
}

int main()
{
    fin >> n >> m >> s;
    while (m--)
    {
        int x, y;
        fin >> x >> y;
        gp[x].push_back(y);
    }
    BFS(s);
    for (int i = 1; i <= n; i++)
        fout << len[i] << ' ';
    fin.close();
    fout.close();
    return 0;
}