Cod sursa(job #2917813)

Utilizator RaresPoinaruPoinaru-Rares-Aurel RaresPoinaru Data 7 august 2022 21:32:52
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("bfs.in");
ofstream fout ("bfs.out");

const int MAXN=100010;
const int MAXM=1000010;

int n,m,s;

int d[MAXN];
vector <int> g[MAXN];
deque <int> dq;

int main()
{
    fin >>n>>m>>s;
    for (int i=1;i<=m;++i){
        int x,y;
        fin >>x>>y;
        if (x!=y)
            g[x].push_back (y);
    }

    dq.push_back (s);
    while (dq.empty ()==false){
        int x=dq.front ();
        dq.pop_front ();
        for (int i=0;i<g[x].size ();++i){
            int y=g[x][i];
            if (d[y]==0){
                d[y]=d[x]+1;
                dq.push_back (y);
            }
        }
    }
    for (int i=1;i<=n;++i){
        if (i==s)
            fout <<0<<' ';
        else{
            if (d[i]==0)
                fout <<-1<<' ';
            else
                fout <<d[i]<<' ';
        }
    }
    fin.close ();
    fout.close ();
    return 0;
}