Cod sursa(job #2890811)

Utilizator PushkinPetolea Cosmin Pushkin Data 16 aprilie 2022 18:18:06
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.36 kb
#include <bits/stdc++.h>
using namespace std;

/**
Graph = (pair):(V, E)
    -> V = {label_1, label_2, ..., label_N} ~ the nodes, labeled
    -> E = {(label_i1, label_j1), (label_i2, label_j2), ..., (label_iM, label_jM)} ~ the edges (oriented or not), which are pairs of nodes
If you can reach any node from any node in the graph, than is:
    -> connected (ro: conex) (unoriented)
    -> strongly connected (ro: tare-conex) (oriented)

Subgraph, Component -> part of the graph
*/

class Graph {
public:
    vector<vector<int>> G;
    bool oriented;

    /// Ctors
    Graph(size_t N, bool oriented) {
        G.resize(N);
        this->oriented = oriented;
    }

    Graph(size_t N, bool oriented, vector<pair<int, int>> edges) {
        Graph(N, oriented);

        for(pair<int, int> edge : edges)
            add_edge(edge.first, edge.second);
    }

    /// Member functions
    void add_edge(int x, int y) {
        G[x].push_back(y);
        if(!oriented)
            G[y].push_back(x);
    }

    size_t size() {
        return G.size();
    }
};

pair<Graph, int> read_graph(string filename_in) {
    ifstream in(filename_in);

    int N;
    int S;

    in >> N >> S >> S;

    Graph graph(N, true);

    int x, y;
    while(in >> x >> y)
        graph.add_edge(x - 1, y - 1);

    in.close();

    return make_pair(graph, S - 1);
}

void BFS(Graph &graph, int source_node, vector<int> &distances) {
    vector<bool> visited;
    queue<int> q;

    visited.resize(graph.size(), false);
    distances.resize(graph.size(), -1);

    q.push(source_node);
    visited[source_node] = true;
    distances[source_node] = 0;

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

        for(int next_node : graph.G[node])
            if(!visited[next_node]) {
                q.push(next_node);
                visited[next_node] = true;
                distances[next_node] = distances[node] + 1;
            }
    }
}

void write_output(vector<int> &distances, string filename_out) {
    ofstream out(filename_out);

    for(int d : distances)
        out << d << ' ';

    out.close();
}

int main()
{
    pair<Graph, int> input = read_graph("bfs.in");

    vector<int> distances;
    BFS(input.first, input.second, distances);

    write_output(distances, "bfs.out");

    return 0;
}