Cod sursa(job #1596563)

Utilizator georgeliviuPereteanu George georgeliviu Data 11 februarie 2016 10:27:18
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <string.h>

using namespace std;

#define Nmax 100010
vector <int> ad[Nmax] ;
queue <int> q ;
bool b[Nmax] ;
int T[Nmax] ;
int n , m , s , x , y ;

void bfs ( int start )
{
    memset(T,-1,sizeof(T)) ;
    q.push(start);
    b[start] = true ;
    T[start] = 0 ;
    while ( !q.empty() )
    {
        int nod = q.front();
        q.pop();
        b[nod] = true ;
        for ( int i = 0 ; i < ad[nod].size() ; ++i )
        {
            if ( !b[ad[nod][i]] )
            {
                q.push(ad[nod][i]);
                T[ad[nod][i]] = T[nod] + 1 ;
            }
        }
    }
}

int main()
{
    freopen("bfs.in","r",stdin);
    freopen("bfs.out","w",stdout);

    scanf("%d %d %d",&n,&m,&s);
    for ( int i = 1 ; i <= m ; i++ )
    {
        scanf("%d %d",&x,&y);
        ad[x].push_back(y) ;
        //ad[y].push_back(x) ;
    }
    bfs(s) ;
    for ( int i = 1 ; i <= n ; i++ )
    {
        printf("%d ",T[i]);
    }
}