Cod sursa(job #1268922)

Utilizator cldmeClaudiu Ion cldme Data 21 noiembrie 2014 17:39:54
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <queue>
using namespace std;

ifstream in ("bfs.in");
ofstream out ("bfs.out");

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];
        }
    }
}

int main()
{
    int i,n,m,x,y,s;
    in>>n>>m>>s;
    for(i=1;i<=m;i++)
    {
        in>>x>>y;
        addEdge(x,y);
    }
    bfs(s);
    for(i=1;i<=n;i++)
    {
        if(cost[i] == 0 && i != s) out<<"-1"<<" ";
        else out<<cost[i]<<" ";
    }
    return 0;
}