Cod sursa(job #2668910)

Utilizator Iustin01Isciuc Iustin - Constantin Iustin01 Data 5 noiembrie 2020 17:49:58
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <bits/stdc++.h>
#define MAX 100005
#define oo (1 << 29)
using namespace std;

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

deque < int  > d;
vector < int > g[MAX];

int n, m, x, y, dist[MAX], sursa;
bitset < MAX > c;

void bfs(int k){
    for(int i = 1; i <= n; i++)
        dist[i] = oo;
    c[k] = true;
    d.push_back(k);
    dist[k] = 0;
    while(!d.empty()){
        k = d.back();
        for(int i = 0; i < g[k].size(); i++)
            if(!c[g[k][i]])
              dist[g[k][i]] = dist[k] + 1,  c[g[k][i]] = true, d.push_front(g[k][i]);
        d.pop_back();

    }
}

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