Cod sursa(job #2217547)

Utilizator AlexDabuDabu Alexandru AlexDabu Data 30 iunie 2018 19:47:56
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#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();
}