Cod sursa(job #2308148)

Utilizator parsulPaul Cristian Banu-Taran parsul Data 26 decembrie 2018 14:47:44
Problema BFS - Parcurgere in latime Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <stdio.h>
#include <stdlib.h>
#define nmax 100000

int m,n,s,*edge[nmax],deg[nmax],cost[nmax];
bool v[nmax];

void bf()
{
    int q[nmax],l,r,*p;
    v[q[l=r=0]=s]=1,cost[s]=0;
    while(l<=r)
    {
        for(p=edge[q[l]];*p!=-1;++p)
            if(!v[*p])
            {
                v[q[++r]= *p]=1;
                cost[*p]=cost[q[l]]+1;
            }
        l++;
    }
}

int main()
{
    int i,x,y;
    freopen("bfs.in","r",stdin);
    freopen("bfs.out","w",stdout);
    scanf("%d %d %d",&n,&m,&s);
    while(m)
    {
        scanf("%d %d",&x,&y);
        deg[x-1]++;
        m--;
    }
    for(i=0;i<n;i++)
    {
        edge[i]=(int *)malloc((deg[i]+1)*sizeof(int));
        edge[i][deg[i]]=-1,deg[i]=0;
    }
    fseek(stdin,0,SEEK_SET);
    scanf("%d %d %d",&n,&m,&s),s--;
    while(m)
    {
        scanf("%d %d",&x,&y);
        x--,y--,edge[x][deg[x]++]=y,m--;
    }
    bf();
    for(i=0;i<n;i++)
        if(cost[i]==0&&i!=s)
            printf("-1 ");
        else
            printf("%d ",cost[i]);
}