Cod sursa(job #2564978)

Utilizator NotTheBatmanBruce Wayne NotTheBatman Data 2 martie 2020 11:25:10
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

const int N = 1e5 + 5, oo = 1e9;

int n, start, d[N];
vector <int> L[N];

void Read ()
{
    int m;
    ifstream fin ("bfs.in");
    fin >> n >> m >> start;
    while (m--)
    {
        int x, y;
        fin >> x >> y;
        L[x].push_back(y);
    }
}

queue <int> q;

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

void Solve ()
{
    for (int i = 1; i <= n; i++)
        d[i] = oo;
    BFS(start);
    ofstream fout ("bfs.out");
    for (int i = 1; i <= n; i++)
        if (d[i] < oo)
            fout << d[i] << " ";
        else fout << "-1 ";
    fout << "\n";
    fout.close();
}

int main()
{
    Read();
    Solve();
    return 0;
}