Cod sursa(job #2196961)

Utilizator georgeromanGeorge Roman georgeroman Data 20 aprilie 2018 19:32:39
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <queue>
#include <vector>

int main() {
  std::ifstream in("bfs.in");
  std::ofstream out("bfs.out");

  unsigned n, m, s;
  in >> n >> m >> s;

  std::vector<std::vector<unsigned>> graph = std::vector<std::vector<unsigned>>();
  graph.reserve(n);
  for (unsigned i = 0; i < n; i++) {
    graph.push_back(std::vector<unsigned>());
  }

  for (unsigned i = 0; i < m; i++) {
    unsigned from, to;
    in >> from >> to;
    graph[from - 1].push_back(to);
  }

  std::vector<bool> visited = std::vector<bool>();
  visited.reserve(n);
  for (unsigned i = 0; i < n; i++) visited.push_back(false);
  std::vector<int> lengths = std::vector<int>();
  lengths.reserve(n);
  for (unsigned i = 0; i < n; i++) lengths.push_back(-1);

  std::queue<unsigned> q = std::queue<unsigned>();
  q.push(s);
  visited[s - 1] = true;
  lengths[s - 1] = 0;

  unsigned currentLength;
  while (!q.empty()) {
    unsigned current = q.front();
    q.pop();
    currentLength = lengths[current - 1];
    for (unsigned v : graph[current - 1]) {
      if (!visited[v - 1]) {
        visited[v - 1] = true;
        lengths[v - 1] = currentLength + 1;
        q.push(v);
      }
    }
  }

  for (int l : lengths) out << l << " ";

  return 0;
}