Cod sursa(job #2864689)

Utilizator DajaMihaiDaja Mihai DajaMihai Data 8 martie 2022 09:23:51
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
#include <vector>
#include <queue>

#define MAX_N 100000

using namespace std;

vector<int> graph[MAX_N + 1];
queue<int> bfsQueue;

int dist[MAX_N + 1];

int N, M, S;

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

void fix(int N){
  for (int i = 1; i <= N; i ++)
    dist[i] = -1;
}

void addEdge(int a, int b){
  graph[a].push_back(b);
}

void bfs(int node){
  dist[node] = 0;
  bfsQueue.push(node);
  while(!bfsQueue.empty()){
    int firstNode = bfsQueue.front();
    for (int neighbour : graph[firstNode]){
      if (dist[neighbour] == -1){
        dist[neighbour] = dist[firstNode] + 1;
        bfsQueue.push(neighbour);
      }
    }
    bfsQueue.pop();
  }
}

int main(){
  in >> N >> M >> S;

  fix(N);

  int a , b;
  for(int i = 0; i < M; i ++){
    in >> a >> b;
    addEdge(a, b);
  }

  bfs(S);

  for (int i = 1; i <= N; i ++)
    out << dist[i] << " ";
  out << '\n';
}