Cod sursa(job #2779808)

Utilizator vmnechitaNechita Vlad-Mihai vmnechita Data 4 octombrie 2021 23:52:19
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>
#define NMAX 100005
#define pb push_back

using namespace std;

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

vector < int > v[NMAX];
queue < int > q;
int dist[NMAX];

void dfs();

int main()
{
    int n, m, x, a, b, i;

    fin >> n >> m >> x;
    while ( m-- )
    {
        fin >> a >> b;
        v[a].pb ( b );
    }

    for ( i = 1; i <= n; i++ ) if ( i != x ) dist[i] = -1;

    q.push ( x );
    dfs();

    for ( i = 1; i <= n; i++ ) fout << dist[i] << ' ';

    return 0;
}

void dfs()
{
    vector < int > :: iterator it;
    int x;

    while ( q.empty() == 0 )
    {
        x = q.front();
        q.pop();

        for ( it = v[x].begin(); it != v[x].end(); it++ ) if ( dist[*it] == -1 ) dist[*it] = dist[x] + 1, q.push ( *it );
    }
}