Cod sursa(job #2576154)

Utilizator MichaelXcXCiuciulete Mihai MichaelXcX Data 6 martie 2020 17:37:31
Problema BFS - Parcurgere in latime Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>

using namespace std;

const char* fin  = "bfs.in";
const char* fout = "bfs.out";

const int NMAX = 1 << 16;

int M, N, startNode;
int dist[NMAX];
vector<int> G[NMAX];
queue<int> Q;

void BFS(int startNode)
{
    for(int i = 1; i <= N; ++i)
        dist[i] = -1;

    dist[startNode] = 0;
    Q.push(startNode);

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

        for(auto& it : G[currNode]) {
            if(dist[it] == -1) {
                dist[it] = dist[currNode] + 1;
                Q.push(it);
            }
        }
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL), cout.tie(NULL);

    freopen(fin, "r", stdin);
    freopen(fout, "w", stdout);

    cin >> N >> M >> startNode;
    for(; M; M--) {
        int x, y;
        cin >> x >> y;

        G[x].push_back(y);
    }

    BFS(startNode);

    for(int i = 1; i <= N; ++i)
        cout << dist[i] << " ";
    return cout << "\n", 0;
}