Cod sursa(job #930475)

Utilizator razvan.popaPopa Razvan razvan.popa Data 27 martie 2013 17:49:29
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include<cstdio>
#include<cstring>
#include<cstdlib>
#define FOR(i,a,b)\
   for(int i=a; i<=b; ++i)
#define infile "bfs.in"
#define outfile "bfs.out"
#define nMax 100005
using namespace std;

int Q[nMax], D[nMax];

int *V[nMax], Deg[nMax];

int N, M, SRC;

void read(){
    freopen(infile, "r", stdin);
    scanf("%d %d %d", &N, &M, &SRC);

    int x, y;
    while(M--){
        scanf("%d %d", &x, &y);

        Deg[x - 1] ++;
    }

    FOR(i,0,N-1){
        V[i] = (int *) malloc((Deg[i]+1) * sizeof(int));
        V[i][Deg[i]] = -1;
        Deg[i] = 0;
    }

    fseek(stdin, 0, SEEK_SET);

    scanf("%d %d %d", &N, &M, &SRC);
    SRC --;

    while(M--){
        scanf("%d %d", &x, &y);

        V[x-1][Deg[x-1] ++] = y-1;
    }

    fclose(stdin);
}


void BFS(){
    memset(D, -1, sizeof(D));
    int l, r, *p;

    D[Q[l = r = 1] = SRC] = 0;

    for(; l <= r; ++l){
        for(p = V[Q[l]]; *p != -1; p ++)
           if(D[*p] == -1)
               D[Q[++r] = *p] = D[Q[l]] + 1;
    }
}

void print(){
    freopen(outfile, "w", stdout);

    FOR(i,0,N-1)
       printf("%d ", D[i]);

    fclose(stdout);
}

int main(){
    read();
    BFS();
    print();

    return 0;
}