Mai intai trebuie sa te autentifici.
Cod sursa(job #1997598)
Utilizator | Data | 4 iulie 2017 22:24:21 | |
---|---|---|---|
Problema | BFS - Parcurgere in latime | Scor | 80 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.4 kb |
#include <fstream>
#include <iostream>
#include <map>
#include <vector>
#include <queue>
using namespace std;
map<int, vector<int> > graf;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int costs[100005];
int visited[100005];
int main() {
int count=0, n, m, s, start, end, components=0;
queue<pair<int, int>> q;
fin >> n >> m >> s;
count = 1;
while (count <= n) {
vector<int> vecini;
graf[count] = vecini;
costs[count] = -1;
++count;
}
count = 0;
while (count < m) {
fin >> start >> end;
graf[start].push_back(end);
++count;
}
pair<int, int> start_node = {s, -1};
q.push(start_node);
while (!q.empty()) {
pair<int, int> node = q.front();
q.pop();
int current_node = node.first;
int parent_node = node.second;
if (visited[current_node]) continue;
if (parent_node == -1 )
costs[current_node] = 0;
else if( costs[current_node] == -1 || costs[current_node] < costs[parent_node] + 1) {
costs[current_node] = costs[parent_node] + 1;
}
for(auto &vecin : graf[current_node]) {
pair<int, int> next_node = {vecin, current_node};
q.push(next_node);
}
visited[current_node] = 1;
}
for(int index=1; index <= n; index++) {
fout << costs[index] << " ";
}
return 0;
}