Cod sursa(job #1965911)

Utilizator SirbuSirbu Ioan Sirbu Data 14 aprilie 2017 18:40:15
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>
#include <vector>
#include <queue>
#define inf 0x3f3f3f3f

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

vector < int > graf[100002];
int dist[100002];
queue < int > q;

void BFS (int n, int s){

  vector < int >::iterator it;
  for (int i = 1; i <= n; ++i)
    dist[i] = inf;

  dist[s] = 0;
  q.push(s);
  while (!q.empty()){
    int nod = q.front();
    q.pop();
    for (it = graf[nod].begin(); it != graf[nod].end(); ++it){
      if (dist[*it] > dist[nod] + 1){
        dist[*it] = dist[nod] + 1;
        q.push(*it);
      }
    }
  }
}


int main (){

  int n,m,s,x,y;
  fin >> n >> m >> s;
  for (int i = 1; i <= m; ++i){
    fin >> x >> y;
    graf[x].push_back(y);
  }

  BFS(n,s);
  for (int i = 1; i <= n; ++i){
    if (dist[i] == inf)
      fout << -1 << " ";
    else fout << dist[i] << " ";
  }

}