Cod sursa(job #285893)

Utilizator AndreiDDiaconeasa Andrei AndreiD Data 23 martie 2009 09:33:17
Problema BFS - Parcurgere in latime Scor 0
Compilator c Status done
Runda Arhiva educationala Marime 1.03 kb
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *a[100001];
int viz[100001];
int n,m,x,y,p,u,s;
int cost[100001];
int s1[100001];

void bfs(int nod)
{
    int i;
    memset(viz,-1,sizeof(viz));
    viz[nod]=0;
    p=u=1;
    s1[p]=nod;
    while(p<=u)
    {
        x=s1[p++];
        for (i=1;i<=a[x][0];++i)
             if (viz[a[x][i]]==-1)
             {
                    s1[++u]=a[x][i];
                    viz[a[x][i]]=viz[x]+1;
            }
    }
}      

int main()
{
    int i;
    freopen("bfs3.in","r",stdin);
    freopen("bfs3.out","w",stdout);
    
    scanf("%d %d %d\n", &n,&m,&s);
    
    for (i=1;i<=n;++i)
    {
        a[i]=(int *) realloc(a[i], sizeof(int));
        a[i][0]=0;
    }
    
    for (i=1;i<=m;++i)
    {
        scanf("%d %d\n", &x,&y);
        a[x][0]++;
        a[x]=(int *) realloc(a[x], (a[x][0]+1)*sizeof(int));
        a[x][a[x][0]]=y;
    }
    
    bfs(s);
    for (i=1;i<=n;++i)
         printf("%d ", viz[i]);
    return 0;
}