Pagini recente » Cod sursa (job #579701) | Cod sursa (job #1129943) | Cod sursa (job #587919) | Cod sursa (job #3238557) | Cod sursa (job #1597493)
#include <fstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <queue>
using namespace std;
template <class T>
class graph {
unordered_map<T, vector<T>> neighbors;
unordered_set<T> nodes;
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;
unordered_set<T> visited;
queue<T> q;
result[node] = 0;
q.push(node);
visited.insert(node);
while (!q.empty()) {
auto x = q.front(); q.pop();
for (auto next : neighbors[x]) {
if (visited.find(next) == visited.end()) {
visited.insert(next);
result[next] = result[x] + 1;
q.push(next);
}
}
}
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;
}