Cod sursa(job #2237906)

Utilizator dragos192k1Dragos-Iulian Galeteanu dragos192k1 Data 3 septembrie 2018 21:50:03
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <cstdio>
#include <cstdlib>
#include <queue>

using namespace std;

int n, m, s, *a[100005], d[100005], checked[100005];
queue <int> vrts;

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

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

    for (int i = 1; i <= n; ++i) {
        a[i] = (int *)realloc(a[i], sizeof(int));
        a[i][0] = 0;
    }

    for (int i = 1; i <= m; ++i) {
        int x, y;
        scanf("%d%d", &x, &y);

        ++a[x][0];
        a[x] = (int *)realloc(a[x], (a[x][0] + 1) * sizeof(int));
        a[x][a[x][0]] = y;
    }

    checked[s] = 1;
    vrts.push(s);

    while (!vrts.empty()) {
        int v = vrts.front();
        vrts.pop();

        for (int i = 1; i <= a[v][0]; ++i) {
            if (!checked[a[v][i]]) {
                checked[a[v][i]] = 1;
                d[a[v][i]] = d[v] + 1;
                vrts.push(a[v][i]);
            }
        }
    }

    for (int i = 1; i <= n; ++i) {
        if (i != s && !d[i]) printf("-1 ");
        else printf("%d ", d[i]);
    }

    fclose(out);
    return 0;
}