Cod sursa(job #2237057)

Utilizator AndreiVisoiuAndrei Visoiu AndreiVisoiu Data 31 august 2018 14:39:20
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

const int NMAX = 100001;
vector<int> a[NMAX];

int c[NMAX], dp[NMAX], n, s;

void bfs(int x) {
    c[1] = x;
    dp[x] = 0;
    int crt, p = 1, u = 1;
    while(p <= u) {
        crt = c[p++];
        for(int i = 0; i < a[crt].size(); i++)
            if(dp[a[crt][i]] == -1) {
                c[++u] = a[crt][i];
                dp[a[crt][i]] = dp[crt]+1;
            }
    }
}

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

    int m, x, y;
    scanf("%i %i %i", &n, &m, &s);

    while(m--) {
        scanf("%i %i", &x, &y);
        a[x].push_back(y);
    }

    for(int i = 1; i <= n; i++)
        dp[i] = -1;

    bfs(s);

    for(int i = 1; i <= n; i++)
        printf("%i ", dp[i]);
    return 0;
}