Cod sursa(job #754938)

Utilizator adalLica Adela adal Data 4 iunie 2012 10:55:32
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <queue>
#include <vector>
#include <stdio.h>
#include <cstring>

#define pb push_back

using namespace std;

vector <int> G[100001];
queue <int> Q;
int N, M, i, x, y, P, Lg[100001];
bool U[100001];

void bfs(int x){

    Q.push(x); Lg[x] = 0; U[x] = true;

    while (!Q.empty()){
        x = Q.front();
        for( i = 0; i < G[x].size(); i++)
           if (!U[G[x][i]])  {
               Q.push(G[x][i]);
               Lg[G[x][i]] = Lg[x]+1;
               U[G[x][i]] = true;
            }
    Q.pop();
    }
}


void load(){
   scanf("%d %d %d\n", &N, &M, &P);
   for (i = 1; i <= M; i++){
     scanf("%d %d\n",&x, &y);
     G[x].pb(y);
 }
 return;
}


int main(){
   freopen("bfs.in","r",stdin);
   freopen("bfs.out","w",stdout);
   load();
   memset(U, false, sizeof(U));
   memset(Lg, 0, sizeof(Lg));
   bfs(P);
   for (i = 1; i<=N ; ++i)
        if( U[i]==0 && i!=P) printf("-1 ");
        else printf("%d ", Lg[i]);
return 0;
}