Cod sursa(job #2987363)

Utilizator matttyzMatei B matttyz Data 2 martie 2023 11:25:04
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream fin ("bfs.in");

vector <vector <int> > L;
int n;

void BFS(int start)
{
    vector <int> dist (n + 1, 2e9);
    dist[start] = 0;
    queue <int> q;
    q.push(start);
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        for (auto next : L[nod])
            if (dist[next] > 1 + dist[nod])
            {
                dist[next] = 1 + dist[nod];
                q.push(next);
            }
    }
    ofstream fout ("bfs.out");
    for (int i = 1; i <= n; i++)
        fout << ((dist[i] == 2e9) ? -1 : dist[i]) << " ";
}

int main ()
{
    int m, start;
    fin >> n >> m >> start;
    L.resize(n + 1);
    while (m--)
    {
        int x, y;
        fin >> x >> y;
        L[x].push_back(y);
    }
    BFS(start);
    return 0;
}