Pagini recente » Cod sursa (job #2503364) | Cod sursa (job #1798621) | Cod sursa (job #2327950) | Cod sursa (job #2747306) | Cod sursa (job #2890812)
#include <bits/stdc++.h>
using namespace std;
/**
Graph = (pair) : (V, E)
-> V = (label_1, label_2, ... label_N) - the nodes, labeled
-> E = (label_1, label j2), (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, then is:
-> connected (conex) (neorientat)
-> strongly conected (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 write_output(vector<int> &distances, string filename_out) {
ofstream out(filename_out);
for (int d : distances)
out << d << ' ';
out.close();
}
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;
}
}
}
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;
}