Pagini recente » Cod sursa (job #695046) | Cod sursa (job #2397364) | Cod sursa (job #484884) | Cod sursa (job #111377) | Cod sursa (job #2217547)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
#define NMAX 100002
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N, M, S;
vector <int> G[NMAX];
int shortest_path[NMAX];
bool inQueue[NMAX];
void read(void)
{
int x, y;
fin >> N >> M >> S;
for (int i = 0; i < M; i++)
{
fin >> x >> y;
if (x != y)
G[x].push_back(y);
}
}
void Dijkstra(void)
{
queue <int> path;
path.push(S);
int node;
while (!path.empty())
{
node = path.front();
inQueue[node] = false;
path.pop();
for (int i = 0; i < G[node].size(); i++)
{
int curr_node = G[node].at(i);
if ((!shortest_path[curr_node] || shortest_path[curr_node] > shortest_path[node] + 1) && curr_node != S)
{
shortest_path[curr_node] = shortest_path[node] + 1;
if (!inQueue[curr_node])
{
inQueue[curr_node] = true;
path.push(G[node].at(i));
}
}
}
}
}
void print(void)
{
for (int i = 1; i <= N; i++)
{
if (shortest_path[i] == 0 && i != S)
{
fout << -1 << ' ';
}
else
{
fout << shortest_path[i] << ' ';
}
}
}
int main(void)
{
read();
Dijkstra();
print();
}