Cod sursa(job #2667691)

Utilizator sebastian.barbarasaSebastian Barbarasa sebastian.barbarasa Data 3 noiembrie 2020 19:02:46
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 100004
using namespace std;

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

vector <int>v[NMAX];
queue <int>q;
int sol[NMAX];
int n, m, s, now;

int main()
{
 int i, x, y;
 fin>>n>>m>>s;
 for (i=1; i<=n; i++)
      sol[i]=-1;
 sol[s]=0;
 for (i=1; i<=m; i++)
     {
      fin>>x>>y;
      v[x].push_back(y);
     }
 q.push(s);
 while (!q.empty())
       {
        now=q.front();
        while (!v[now].empty())
              {
               if (sol[v[now].back()]==-1)
                  {
                   sol[v[now].back()]=sol[now]+1;
                   q.push(v[now].back());
                  }
               v[now].pop_back();
              }
        q.pop();
       }
 for (i=1; i<=n; i++)
      fout<<sol[i]<<' ';
 fout<<'\n';
 fin.close();
 fout.close();
 return 0;
}