Cod sursa(job #2670144)

Utilizator As932Stanciu Andreea As932 Data 9 noiembrie 2020 10:01:12
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nMax = 100005;

int n, m, s;
int ans[nMax];
bool viz[nMax];
vector <int> muchii[nMax];

void read(){
    fin >> n >> m >> s;

    for(int i = 1; i <= m; i++){
        int x, y;

        fin >> x >> y;

        muchii[x].push_back(y);
    }
}

void bfs(){
    queue <int> q;

    q.push(s);
    viz[s] = 1;

    while(!q.empty()){
        int nod = q.front();
        q.pop();

        for(int i = 0; i < muchii[nod].size(); i++)
            if(!viz[muchii[nod][i]]){
                viz[muchii[nod][i]] = 1;
                q.push(muchii[nod][i]);
                ans[muchii[nod][i]] = ans[nod] + 1;
            }
    }
}

void print_ans(){
    for(int i = 1; i <= n; i++)
        if(ans[i])
            fout << ans[i] << " ";
        else if(i == s)
            fout << 0 << " ";
        else
            fout << -1 << " ";
}

int main()
{
    read();
    bfs();
    print_ans();

    return 0;
}