Cod sursa(job #1604750)

Utilizator andreitulusAndrei andreitulus Data 18 februarie 2016 15:43:46
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include<stdio.h>
#define nmax 100003
using namespace std;

struct nod{int inf; nod *urm;};

nod *L[nmax], *R[nmax];

int n, m, s, c[nmax], d[nmax], v[nmax];

void add(int sr, int val)
{
    nod *q;
    q = new nod;
    q->inf = val;
    q->urm = NULL;

    if(L[sr] == NULL)
        L[sr] = R[sr] = q;
    else
        {
            R[sr]->urm = q;
            R[sr] = q;
        }
}



void read()
{
    int i, n1, n2;

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

    for(i = 1; i <= m; i++)
    {
        scanf("%d %d", &n1, &n2);

        add(n1, n2);
    }
}



void BFS(int s)
{
    int p, u, k, i;
    nod *q;

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

    v[s] = 1;
    p = u = 1;
    c[u] = s;
    d[s] = 0;


    while(p <= u)
    {
        k = c[p];

        for(q = L[k]; q != NULL; q = q->urm)
            if(v[q->inf] == 0)
            {
                v[q->inf] = 1;

                u++;
                c[u] = q->inf;

                d[q->inf] = d[k] + 1;
            }


       p++;
    }
}



void afis()
{
    int i;

    for(i = 1; i <= n; i++)
        printf("%d ", d[i]);
}




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

    read();

    BFS(s);

    afis();

    fclose(stdin);
    fclose(stdout);

    return 0;
}