Cod sursa(job #1502899)

Utilizator andreiblaj17Andrei Blaj andreiblaj17 Data 15 octombrie 2015 09:36:06
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

#define nmax 100001
#define inf 1<<30

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

int n, m, s;
int a, b;
int Cost[nmax];

vector <int> G[nmax];
queue <int> q;

void read()
{

    fi >> n >> m >> s;

    for (int i = 1; i <= m; i++)
    {
        fi >> a >> b;
        G[a].push_back(b);
    }

}

void init()
{
    q.push(s);
    for (int i = 1; i <= n; i++)
        Cost[i] = inf;
    Cost[s] = 0;
}

void bfs()
{

    init();

    while (!q.empty())
    {

        int nodulCurent = q.front();

        q.pop();

        for (int i = 0; i < G[nodulCurent].size(); i++)
        {

            int vecin = G[nodulCurent][i];

            if (Cost[vecin] > Cost[nodulCurent] + 1)
            {
                Cost[vecin] = Cost[nodulCurent] + 1;
                q.push(vecin);
            }

        }

    }

}

void write()
{
    for (int i = 1; i <= n; i++)
    {
        if (Cost[i] == inf)
            Cost[i] = -1;
        fo << Cost[i] << " ";
    }
}

int main()
{

    read();

    bfs();

    write();

    return 0;
}