Cod sursa(job #1268912)

Utilizator cldmeClaudiu Ion cldme Data 21 noiembrie 2014 17:31:56
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <stdio.h>
#include <queue>
using namespace std;
int const N=100001;

int nodes[N], next[N], last[N],nr =0, cost[N];
queue<int> q;

void addEdge(int x,int y)
{
    ++nr;
    nodes[nr] = y;
    next[nr] = last[x];
    last[x] = nr;
}

void bfs(int s)
{
    int x,currentNode;
    cost[s] = 0;
    q.push(s);
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        currentNode = x;
        x = last[x];
        while(x != 0)
        {
            if(cost[nodes[x]] == 0 && nodes[x] != s)
            {
                cost[nodes[x]] = cost[currentNode] + 1;
                q.push(nodes[x]);
            }
            x = next[x];
        }
    }
}

void afisare(int i)
{
    int x;
    printf("%d -> ",i);
    x = last[i];
    while(x != 0)
    {
        printf("%d ",nodes[x]);
        x = next[x];
    }
    printf("\n");
}

int main()
{
    int i,n,m,x,y,s;
    freopen("bfs.in","r",stdin);
    freopen("bfs.out","w",stdout);
    scanf("%d %d %d",&n,&m,&s);
    for(i=1;i<=m;i++)
    {
        scanf("%d %d\n",&x,&y);
        addEdge(x,y);
    }
    bfs(s);
    for(i=1;i<=n;i++)
    {
        if(cost[i] == 0 && i != s) printf("-1 ");
        else printf("%d ",cost[i]);
    }
    return 0;
}