Cod sursa(job #997648)

Utilizator robertstrecheStreche Robert robertstreche Data 14 septembrie 2013 17:55:54
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");

int n,m,y,x,i,p,u,xx,b[100001];
int a[100001];
vector <int> v[100001];

int main()
{
    f>>n>>m>>xx;
    for (i=1;i<=m;i++)
     {
         f>>y>>x;
         v[y].push_back(x);

     }
     p=1;
     u=1;
     a[xx]=1;
     b[p]=xx;

     while (p<=u)
      {
          if (v[b[p]].size()>0)
          {for (i=0;i<=v[b[p]].size()-1 ;i++)

               if (a[v[b[p]][i]]==0)
                {
                    u++;
                    b[u]=v[b[p]][i];
                    a[v[b[p]][i]]=a[b[p]]+1;

                }
          }
           p++;
      }

      for (i=1;i<=n;i++)
       if (a[i])g<<a[i]-1<<" ";
       else g<<"-1 ";
   f.close();
   g.close();
}