Pagini recente » Cod sursa (job #1136417) | Cod sursa (job #3283226) | Istoria paginii preoni-2006/runda-2/clasament-11-12 | Cod sursa (job #260099) | Cod sursa (job #1597483)
#include <fstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
template <class T>
class graph {
unordered_map<T, vector<T>> neighbors;
unordered_set<T> nodes;
void breadth_first_search(T node, unordered_map<T, int>& depth, int d) {
static unordered_set<T> visited;
if (visited.find(node) != visited.end()) {
return;
}
visited.insert(node);
depth[node] = d;
for (auto next : neighbors[node]) {
breadth_first_search(next, depth, d + 1);
}
}
public:
template <class Iterator>
graph(Iterator begin, Iterator end):
nodes(begin, end) {}
void add_edge(T src, T dst) {
neighbors[src].push_back(dst);
}
unordered_map<T, int> breadth_first_search(T node) {
unordered_map<T, int> result;
breadth_first_search(node, result, 0);
for (auto other : nodes) {
if (other != node && result[other] == 0)
result[other] = -1;
}
return result;
}
};
int main() {
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s;
fin >> n >> m >> s;
vector<int> nodes;
for (int i = 1; i <= n; ++i) {
nodes.push_back(i);
}
graph<int> G(nodes.begin(), nodes.end());
for (int i = 0; i < m; ++i) {
int src, dst;
fin >> src >> dst;
G.add_edge(src, dst);
}
auto result = G.breadth_first_search(s);
for (auto x : nodes) {
fout << result[x] << " ";
}
fout << endl;
return 0;
}