Cod sursa(job #228312)

Utilizator DastasIonescu Vlad Dastas Data 6 decembrie 2008 22:38:32
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <cstdio>

const int maxn = 100001;

FILE *in = fopen("bfs.in","r"), *out = fopen("bfs.out","w");

struct graf
{
    int nod;

    graf *next;
};

int n, m, s;
graf *a[maxn];
int v[maxn], c[maxn];

void add(int what, int where)
{
    graf *q = new graf;

    q->nod = what;
    q->next = a[where];
    a[where] = q;
}

void read()
{
    fscanf(in, "%d %d %d", &n, &m, &s);

    int x, y;

    for ( int i = 0; i < m; ++i )
    {
        fscanf(in, "%d %d", &x, &y);

        add(y, x);
    }
}

void bfs()
{
    for ( int i = 1; i <= n; ++i )
        v[i] = -1;

    v[s] = 0;

    int p = 0, u = 0;
    c[p] = s;

    while ( p <= u )
    {
        int x = c[p++];

        graf *q = a[x];

        while ( q )
        {
            if ( v[q->nod] == -1 )
            {
                v[q->nod] = v[x] + 1;
                c[++u] = q->nod;
            }

            q = q->next;
        }
    }

    for ( int i = 1; i <= n; ++i )
        fprintf(out, "%d ", v[i]);
}

int main()
{
    read();
    bfs();

    return 0;
}