Cod sursa(job #2446676)

Utilizator AndreiJJIordan Andrei AndreiJJ Data 10 august 2019 13:39:35
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

vector <int> L[100005];
queue <int> q;

int dist[100005];
int n, m, k;
const int oo = 1e9;

void Read ()
{
    fin >> n >> m >> k;
    int i, j;
    while (m--)
    {
        fin >> i >> j;
        L[i].push_back(j);
    }
}

void Initiate ()
{
    for (int i = 0; i <= n; i++)
        dist[i] = oo;
}

void BFS (int x)
{
    q.push(x);
    dist[x] = 0;
    while (!q.empty())
    {
        x = q.front();
        q.pop();
        for (auto i : L[x])
            if (dist[i] > 1 + dist[x])
            {
                q.push(i);
                dist[i] = 1 + dist[x];
            }
    }
}

void Write ()
{
    for (int i = 1; i <= n; i++)
        if (dist[i] < oo)
            fout << dist[i] << " ";
        else fout << "-1 ";
}

int main()
{
    Read();
    Initiate();
    BFS(k);
    Write();
    return 0;
}