Cod sursa(job #2649846)

Utilizator marius004scarlat marius marius004 Data 16 septembrie 2020 17:02:48
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

const int NMAX = 100'001;
const int INF = (1 << 30);

int n, m, x, vis[NMAX], cnt;
vector < int > G[NMAX];

void bfs(const int& startNode) {

    queue < int > q;
    q.push(startNode);

    for(int i = 1;i <= n;++i)
        vis[i] = INF;

    vis[startNode] = 1;

    while(!q.empty()) {

        int node = q.front();
        q.pop();

        for(int neighbour : G[node]) {
            if(vis[neighbour] > vis[node] + 1) {
                vis[neighbour] = vis[node] + 1;
                q.push(neighbour);
            }
        }

    }
}

int main() {

    f >> n >> m >> x;

    while(m--) {
        int x, y;
        f >> x >> y;

        G[x].push_back(y);
    }

    bfs(x);

    for(int i = 1;i <= n;++i)
        g << (vis[i] == INF ? -1 : vis[i] - 1) << ' ';

    return 0;
}