Cod sursa(job #2670375)

Utilizator etohirseCristi Cretu etohirse Data 9 noiembrie 2020 19:30:24
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <vector>
#include <queue>

std::ifstream fin("bfs.in");
std::ofstream fout("bfs.out");

const int mxn = 1e5 + 5;

int n, m, S;
std::vector < int > muchii[mxn];
std::queue < int > cords;

int dist[mxn];

void BFS()
{
    int Node, Next;
    while(!cords.empty())
    {
        Node =  cords.front();
        cords.pop();
        for(unsigned int i = 0; i < muchii[Node].size(); i++)
        {
            Next = muchii[Node][i];
            if(dist[Next] == -1)
            {
                cords.push(Next);
                dist[Next] = dist[Node] + 1;
            }
        }
    }
}

void solve(){
	fin >> n >> m >> S;
  for(int i = 1; i <= m; ++i){
      int x, y;
      fin >> x >> y;
      muchii[x].push_back(y);
  }
  for(int i = 1; i <= n; ++i)
      dist[i] = -1;
  dist[S] = 0;
  cords.push(S);
  BFS();
  for(int i = 1; i <= n; ++i)
      fout << dist[i] << " ";
}

int main(){
	solve();
	return 0;
}