Cod sursa(job #2478349)

Utilizator E1goBack Andrei-Gheorghe E1go Data 21 octombrie 2019 22:19:22
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
using namespace std;

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

struct nod{int info;
            nod *urm, *ult;}*v[100001];
vector <int> viz;
queue <int> C;

int main()
{
    int n, x, m, a, b;
    fin>>n>>m>>x;
    viz.resize(n+1);
    while(m)
    {
       fin>>a>>b;
       if(v[a] == NULL)
       {
           v[a]=new nod;
           v[a] -> urm = NULL;
           v[a] -> info = b;
           v[a] -> ult = v[a];
       }
       else
       {
           nod *p;
           p=new nod;
           p->urm = NULL;
           p->info = b;
           v[a] -> ult -> urm = p;
           v[a]->ult=p;
       }
       m--;
    }

    C.push(x);
    viz[x]=1;
    while(! C.empty())
    {
        nod *p;
        for(p=v[C.front()]; p!=NULL; p=p->urm)
         if(viz[p->info] == 0)
         {
            viz[p->info]=viz[C.front()]+1;
            C.push(p->info);
         }
        C.pop();
    }

    for(int i=1; i<=n; i++)
        fout<<viz[i]-1<<" ";
    return 0;
}