Cod sursa(job #3370765)

Utilizator RapiesNechifor Rares-Gabriel Rapies Data 27 octombrie 2026 11:13:17
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, X, i, j, t[100005];
bool v[100005];
vector<int> MC[100005];
queue<int> Q;

void BFS(int x)
{
    v[x] = 1;
    t[x] = 0;
    Q.push(x);
    while(!Q.empty())
    {
        int k = Q.front();
        Q.pop();
        for(auto it = MC[k].begin(); it < MC[k].end(); it++)
            if(v[*it] == 0)
            {
                v[*it] = 1;
                t[*it] = t[k] + 1;
                Q.push(*it);
            }
    }
}

int main()
{
    fin >> n >> m >> X;
    for(int k = 1; k <= m; ++k)
    {
        fin >> i >> j;
        MC[i].push_back(j);
    }
    BFS(X);
    for(i = 1; i <= n; ++i)
        if(v[i] == 0)
            fout << -1 << " ";
        else
            fout << t[i] << " ";
    return 0;
}