Cod sursa(job #600705)

Utilizator mavroMavrodin Bogdan-Florentin mavro Data 2 iulie 2011 21:48:26
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <stdio.h>
#include <vector>
#include <deque>

#define N 100001

using namespace std;

vector <int> Noduri[N];
int n, m, s, cost[N];

void BFS()
{
    int i, nod_curent;
    deque <long int> Q;
    memset(cost, -1, sizeof(cost));

    Q.push_back(s);
    cost[s] = 0;

    while(!Q.empty())
    {
        nod_curent = Q.back();
        Q.pop_back();
        for(i = 0; i < Noduri[nod_curent].size(); i++)
            if(cost[Noduri[nod_curent][i]] < 0)
            {
                cost[Noduri[nod_curent][i]] = cost[nod_curent] + 1;
                Q.push_back(Noduri[nod_curent][i]);
            }
    }
}

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

    scanf("%ld %ld %ld", &n, &m, &s);

    int x, y, i;

    for(i = 0; i < m; i++)
    {
        scanf("%ld %ld", &x, &y);
        Noduri[x].push_back(y);
    }

    BFS();

    for(i = 1; i <= n; i++)
        printf("%ld ", cost[i]);
    printf("\n");

    return 0;
}