Cod sursa(job #2237052)

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

using namespace std;

const int NMAX = 100001;
vector<int> a[NMAX];
queue<int> c;
int g[NMAX], dp[NMAX], n, s;

void bfs(int x) {
    c.push(x);
    dp[x] = 0;
    int crt;
    while(!c.empty()) {
        crt = c.front();
        c.pop();
        for(int i = 0; i < g[crt]; i++)
            if(dp[a[crt][i]] == -1) {
                c.push(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);
        g[x]++;
    }

    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;
}