Pagini recente » Cod sursa (job #2978001) | Cod sursa (job #1626644) | Cod sursa (job #2606367)
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int nr;
vector<Node*> neigh;
Node(int x) {
nr = x;
}
Node() {
nr = -1;
}
};
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
int n;
int m;
int s;
vector<Node*> nodes;
void read_input() {
ifstream fin("bfs.in");
fin >> n >> m >> s;
--s;
for (int i = 0; i < n; ++i)
nodes.emplace_back(new Node(i));
for (int i = 0; i < m; ++i) {
int x, y;
fin >> x >> y;
nodes[x - 1]->neigh.push_back(nodes[y - 1]);
}
fin.close();
}
vector<int> get_result() {
vector<int> dist(n, -1);
dist[s] = 0;
queue<int> q;
q.push(s);
int curr, d;
while (!q.empty()) {
curr = q.front();
d = dist[curr] + 1;
q.pop();
for (auto it : nodes[curr]->neigh) {
if (dist[it->nr] == -1) {
dist[it->nr] = d;
q.push(it->nr);
}
}
}
return dist;
}
void print_output(vector<int> result) {
ofstream fout("bfs.out");
int q = result.size();
for (int i = 0; i < q; ++i) {
fout << result[i] << ' ';
}
fout.close();
}
};
// Please always keep this simple main function!
int main() {
// Allocate a Task object on heap in order to be able to
// declare huge static-allocated data structures inside the class.
Task *task = new Task();
task->solve();
delete task;
return 0;
}