Cod sursa(job #2924821)

Utilizator BluThund3rRadu George BluThund3r Data 11 octombrie 2022 17:01:56
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream in("bfs.in");
ofstream out("bfs.out");



int main() {
    int n, m, s, x, y;

    queue<pair<int, int>> q;

    in >> n >> m >> s;
    vector<vector<int>> adj(n + 1);
    vector<int> dist(n + 1, -1);
    vector<bool> viz(n + 1, false);
    while(m --) {
        in >> x >> y;
        adj[x].push_back(y);
    }

    q.push({s, 0});
    dist[s] = 0;
    viz[s] = true;
    while(!q.empty()) {
        int currNode = q.front().first;
        int currDist = q.front().second;
        q.pop();
        for(auto nextNode : adj[currNode])
            if(!viz[nextNode]) {
                viz[nextNode] = true;
                dist[nextNode] = currDist + 1;
                q.push({nextNode, dist[nextNode]});
            }
    }

    for(int i = 1; i <= n; ++ i)
        out << dist[i] << ' ';


    return 0;
}