Cod sursa(job #2566842)

Utilizator nTropicManescu Bogdan Constantin nTropic Data 3 martie 2020 13:17:24
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>

using namespace std;

const int len = 100005;
//const int inf = 1 << 30;
int m, n, start, x, y, dist[len];
vector<int> g[len];
//vector<int> sol;
queue<int> q;

void bfs(int start) {
    for (int i = 1; i <= n; i++)
        dist[i] = -1;
    dist[start] = 0;
    q.push(start);

    while (!q.empty()) {
        int curr = q.front();
        q.pop();

        for (auto next : g[curr])
            if (dist[next] == -1) {
                dist[next] = dist[curr] + 1;
                q.push(next);
                //sol.push_back(next);
            }
    }
}

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

    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);

    cin >> n >> m >> start;
    for (int i = 1; i <= m; i++) {
        cin >> x >> y;
        g[x].push_back(y);
    }

    bfs(start);

    for (int i = 1; i <= n; i++)
        cout << dist[i] << " ";
    cout << "\n";

    //for (int it : sol)
    //    cout << it << " ";
}