Cod sursa(job #3121893)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 15 aprilie 2023 23:29:20
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>
#define MAXN 100000

using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

int n, m, start, costs[MAXN];
vector<vector<int>> adj;

void read() {
    fin >> n >> m >> start;
    start--;
    adj = vector<vector<int>>(n, vector<int>());
    for (int i = 0; i < m; i++) {
        int iNode, jNode;
        fin >> iNode >> jNode;
        iNode--; jNode--;
        adj[iNode].push_back(jNode);
    }
}

void solve() {
    memset(costs, -1, n * sizeof(int));
    queue<int> neighbours;
    neighbours.push(start);
    costs[start] = 0;
    while (!neighbours.empty()) {
        int current = neighbours.front(); neighbours.pop();
        for (auto& neighbour: adj[current])
            if (costs[neighbour] == -1) {
                costs[neighbour] = costs[current] + 1;
                neighbours.push(neighbour);
            }
    }

    for (int i = 0; i < n; i++)
        fout << costs[i] << ' ';
}

int main() {
    read();
    solve();
    return 0;
}