Cod sursa(job #2964622)

Utilizator samyro14Samy Dragos samyro14 Data 13 ianuarie 2023 15:23:02
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("bfs.in");
ofstream  fout("bfs.out");
#define ll long long
#define pb push_back
#define fast_read  ios :: sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr)
const int maxn = 1e5;
const int maxm = 1e4;
#define INF 0x3f3f3f3f
int n, m, s;
vector<int> a[maxn + 2];
int d[maxn + 2];
void read(){
    fin >> n >> m >> s;
    for(int i = 1; i <= m; ++i){
        int x, y; fin >> x >> y;
        a[x].pb(y);
    }
}
void bfs(int start){
    for(int i = 1; i <= n; ++i)
        d[i] = -1;
    queue<int> q;
    q.push(start);
    d[start] = 0;
    while(!q.empty()){
        int i = q.front();
        q.pop();
        for(auto x : a[i]){
            if(d[x] == -1){
                d[x] = d[i] + 1;
                q.push(x);
            }
        }
    }
}
int main(){
    read();
    bfs(s);
    for(int i = 1; i <= n; ++i)
        fout << d[i] << " ";
    return 0;
}
/*

*/