Cod sursa(job #986826)

Utilizator AndrewTheGreatAndrei Alexandrescu AndrewTheGreat Data 19 august 2013 16:10:18
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 0.74 kb
#include <iostream>
#include <stdio.h>
#include <vector>
#include <queue>
#define pb push_back

using namespace std;

const int nmax = 100100;
vector<int> G[nmax];
queue <int> Q;
int Seen[nmax];

int main () {

    freopen ("bfs.in", "r", stdin);
    freopen ("bfs.out", "w", stdout);
    
    int N, M, S, x, y, i;
    cin >> N >> M >> S;

    while(M--) {
        cin >> x >> y;
        G[x].pb(y);
    }

    Q.push(S);
    Seen[S] = 1;
    while(!Q.empty()) {
        S = Q.front();
        Q.pop();
        for(i = 0; i < G[S].size(); i++)
            if(Seen[G[S][i]] == 0) {
                Q.push(G[S][i]);
                Seen[G[S][i]] = Seen[S] + 1;
            }
    }
    for(i = 1; i <= N; i++)
        cout << Seen[i] - 1 << " ";
    return 0;
}