Cod sursa(job #2960446)

Utilizator Teodor11Posea Teodor Teodor11 Data 4 ianuarie 2023 13:58:05
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
using namespace std;

const int MAX_SIZE = 100001;
int n, m, s;
deque<int> nodes, neighbors[MAX_SIZE];
vector<int> cost;

void graph_traversal(int node)
{
    for (int i = 0; i <= n; ++i)
    {
        cost.push_back(-1);
    }
    cost[node] = 0;
    nodes.push_back(node);
    while (!nodes.empty())
    {
        /*
        cout << "Nodes: ";
        for (auto i = nodes.begin(); i != nodes.end(); ++i) {
            cout << *i << ' ';
        }
        cout << "\n\nCost: ";
        for (int i = 1; i <= n; ++i) {
            cout << '[' << i << "] " << cost[i] << ' ';
        }
        cout << "\n\n";
        */
        int curr_node = nodes.front();
        nodes.pop_front();
        for (auto i = neighbors[curr_node].begin(); i != neighbors[curr_node].end(); ++i)
        {
            if (cost[*i] == -1)
            {
                cout << *i << endl;
                nodes.push_back(*i);
                cost[*i] = cost[curr_node] + 1;
            }
        }
    }
}

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