Cod sursa(job #1855251)

Utilizator LazarAndreiLazar Andrei Teodor LazarAndrei Data 23 ianuarie 2017 15:47:26
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>
using namespace std;

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

const int NMAX = 100001;

queue <int> Q;
vector <int> L[NMAX];
vector <int> :: iterator it ;
int N , M , X , cost[NMAX];

void read_input ()
{
    int node1, node2;
    in >> N >> M >> X;
    for(int i = 1 ; i <= M ; ++ i)
    {
        in >> node1 >> node2;
        L[node1].push_back(node2);
    }
    for(int i = 1 ; i <= N ; ++ i)
        cost[i] = -1;
}

void BFS ()
{
    int node;
    Q.push (X);
    cost[X] = 0;

    while(!Q.empty())
    {
        node = Q.front();
        Q.pop();

        for (it = L[node].begin() ; it != L[node].end() ; ++ it)
        {
            if(cost[*it] == -1)
             {
                   cost[*it] = cost[node] + 1;
                   Q.push(*it);
             }
        }
    }
}

int main()
{
    read_input();
    BFS ();

    for(int i = 1 ; i <= N ; ++ i)
        out << cost[i] << " ";
    return 0;
}