Pagini recente » Cod sursa (job #932095) | Rating Daniel Mirel (wweradu) | Cod sursa (job #918432) | Cod sursa (job #1181056) | Cod sursa (job #2636844)
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
using namespace std;
int const maxSize = 200002;
queue<int>que;
vector<int> adjacency[maxSize];
vector<int> dist(maxSize, 0);
int visited[maxSize], n, m, s;
ifstream f("bfs.in");
ofstream h("bfs.out");
void Read()
{
f >> n >> m >>s;
for (int i = 1; i <= m; i++)
{
int x, y;
f >> x >> y;
adjacency[x].push_back(y);
}
}
void BFS()
{
visited[s] = 1;
que.push(s);
while (!que.empty())
{
int node = que.front();
int length = adjacency[node].size();
que.pop();
for (int i = 0; i < length; i++)
{
if (!visited[adjacency[node][i]])
{
dist[adjacency[node][i]] = dist[node] + 1;
visited[adjacency[node][i]] = 1;
que.push(adjacency[node][i]);
}
}
}
}
void Print()
{ /* Print the nodes that are not visited (in case I look at this 2-3 years from now)*/
bool printed_something = false;
for (int i = 1; i <= n; i++)
{
if (dist[i] == 0 && i != s)
h << "-1" << ' ';
else h << dist[i]<<' ';
}
}
int main()
{
Read();
BFS();
Print();
return 0;
}