Cod sursa(job #1028374)

Utilizator tsubyRazvan Idomir tsuby Data 13 noiembrie 2013 22:12:17
Problema BFS - Parcurgere in latime Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
///numarul minim de arce ce trebuie parcurse de la nodul S la toate nodurile; graf orientat
#include <cstdio>
#include <cstring>
#define NMAX 100000

using namespace std;

int n, m, start_node;
int coada[NMAX], cost[NMAX];
struct nod
{
    int value;
    nod *next;
}*a_list[NMAX]; /// adjacent list

void add(nod *&dest, int val)
{
    nod *p = new nod;
    p -> value = val;
    p -> next = dest;
    dest = p;
}

void BFS(int start)
{
    int i;
    memset(cost, -1, sizeof(cost));
    int length = 1; /// lungime coada
    cost[start] = 0;
    coada[length] = start;

    for(i = 1; i <= length; i++)
        for(nod *j = a_list[coada[i]]; j != NULL; j = j->next)
            if(cost[j -> value] == -1)
            {
                coada[++length] = j -> value;
                cost[coada[length]] = cost[coada[i]] + 1;
            }
}

int main()
{
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
    scanf("%d %d %d", &n, &m, &start_node);
    int x, y;
    for(int i = 0; i < m; i++)
    {
        scanf("%d %d", &x, &y);
        add(a_list[x], y);
    }
    BFS(start_node);
    for(int i = 1; i <= n; i++)
        printf("%d ", cost[i]);
    printf("\n");
    return 0;
}