Cod sursa(job #1867647)

Utilizator preda.andreiPreda Andrei preda.andrei Data 4 februarie 2017 11:30:01
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

struct Node
{
    int cost = -1;
    vector<int> edges;
};

using Graph = vector<Node>;

void Bfs(Graph &g, int start)
{
    queue<int> q;
    q.push(start);
    g[start].cost = 0;

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

        for (int next : g[node].edges) {
            if (g[next].cost == -1) {
                g[next].cost = g[node].cost + 1;
                q.push(next);
            }
        }
    }
}

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

    int n, m, s;
    fin >> n >> m >> s;

    Graph graph(n);
    while (m--) {
        int x, y;
        fin >> x >> y;
        graph[x - 1].edges.push_back(y - 1);
    }

    Bfs(graph, s - 1);
    for (const auto &node : graph) {
        fout << node.cost << " ";
    }
    fout << "\n";

    return 0;
}