Cod sursa(job #3258037)

Utilizator Barbu_MateiBarbu Matei Barbu_Matei Data 20 noiembrie 2024 17:13:13
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <bits/stdc++.h>
using namespace std;

int n, m, s;
vector<vector<int>> v(100001);
int path[100001];

void bfs() {
    memset(path, -1, sizeof(path));
    path[s] = 0;
    queue<int> q;
    q.push(s);
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        for (int i = 0; i < v[node].size(); ++i) {
            if (path[v[node][i]] == -1) {
                q.push(v[node][i]);
                path[v[node][i]] = path[node] + 1;
            }
        }
    }
}

int main() {
    ifstream cin("bfs.in");
    ofstream cout("bfs.out");
    cin >> n >> m >> s;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        cin >> x >> y;
        v[x].push_back(y);
    }
    bfs();
    for (int i = 1; i <= n; ++i) {
        cout << path[i] << " ";
    }
}