Cod sursa(job #1380100)

Utilizator misu007Pogonaru Mihai misu007 Data 6 martie 2015 21:58:53
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <cstdio>
#include <queue>
using namespace std;

int n,cost[100001];

struct nod
{
    int x;
    nod* u;
}*a[100001];

void bfs(int s)
{
    int x;
    nod* nd=a[s];
    queue <int> q;
    for(x=1;x<=n;++x) cost[x]=-1;
    cost[s]=0;
    q.push(s);
    while(!q.empty())
    {
        x=q.front();
        nd=a[x];
        while(nd)
        {
            if(cost[nd->x]==-1)
            {
                cost[nd->x]=cost[x]+1;
                q.push(nd->x);
            }
            nd=nd->u;
        }
        q.pop();
    }
}

int main()
{
    int m,s,x;
    nod *nd;
    freopen("bfs.in","r",stdin);
    freopen("bfs.out","w",stdout);
    scanf("%d%d%d",&n,&m,&s);
    while(m)
    {
        --m;
        scanf("%d",&x);
        nd=new nod;
        nd->u=a[x];
        a[x]=nd;
        scanf("%d",&x);
        nd->x=x;
    }
    bfs(s);
    for(x=1;x<=n;++x)
    {
        printf("%d ",cost[x]);
    }
    printf("\n");
    return 0;
}