Cod sursa(job #2640002)

Utilizator Iustin01Isciuc Iustin - Constantin Iustin01 Data 4 august 2020 17:29:11
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.72 kb
#include <bits/stdc++.h>
#define MAX 1000005
using namespace std;

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

vector < int > g[MAX];
int n, m, x, y, s, dist[MAX];
bitset < MAX > c;
deque < int > d;

void bfs(int k){
    d.push_back(k);

    while(!d.empty()){
        k = d.front();
        c[k] = true;
        d.pop_front();
        for(int i = 0; i < g[k].size(); i++)
            if(!c[g[k][i]])
                d.push_back(g[k][i]), dist[g[k][i]] = dist[k] + 1;
    }
}

int main(){
    in>>n>>m>>s;
    for(int i = 1; i <= m; i++){
        in>>x>>y;
        g[x].push_back(y);
    }
    bfs(s);
    for(int i = 1; i <= n; i++)
        out<<(dist[i] == 0 && i != s ? -1 : dist[i])<<" ";
}