Cod sursa(job #2923670)

Utilizator Teodor11Posea Teodor Teodor11 Data 17 septembrie 2022 17:59:22
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <deque>
using namespace std;

deque<int> neighbors[100001], nodes;
int n, m, s, x, y, neighbors_number[100001], cost[100001];

void BFS(int node) {
    for (int i = 1; i <= n; ++i) {
        cost[i] = -1;
    }
    cost[node] = 0;
    nodes.push_back(node);
    while (!nodes.empty()) {

        cout << "Nodes: ";
        for (int i = 0; i < nodes.size(); ++i) {
            cout << nodes[i] << ' ';
        }
        cout << "\n\nCost: ";
        for (int i = 1; i <= n; ++i) {
            cout << '[' << i << "] " << cost[i] << ' ';
        }
        cout << "\n\n";

        for (int i = 0; i < neighbors_number[nodes.front()]; ++i) {
            if (cost[neighbors[nodes.front()][i]] == -1) {
                nodes.push_back(neighbors[nodes.front()][i]);
                cost[neighbors[nodes.front()][i]] = cost[nodes.front()] + 1;
            }
        }
        nodes.pop_front();
    }
}

int main() {
    ifstream fin("bfs.in");
    ofstream fout("bfs.out");
    fin >> n >> m >> s;
    for (int i = 0; i < m; ++i) {
        fin >> x >> y;
        neighbors[x].push_back(y);
        ++neighbors_number[x];
    }
    BFS(s);
    for (int i = 1; i <= n; ++i) {
        fout << cost[i] << ' ';
    }
    return 0;
}