Cod sursa(job #2304949)

Utilizator dey44andIoja Andrei-Iosif dey44and Data 18 decembrie 2018 21:07:37
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <vector>

#define NMAX 100005

using namespace std;

ifstream in("bfs.in");
ofstream out("bfs.out");

//  Queue implementation
struct nod
{
	int info;
	nod* next;
};
typedef nod* coada;
bool Queue_Empty(coada head, coada tail)
{
	if (!head && !tail) return true;
	return false;
}
int Queue_Front(coada head, coada tail)
{
	 if(head && tail) return head->info;
}
void Push_Back(coada &head, coada &tail, int inf)
{
	coada aux = new nod;
	aux->info = inf;
	aux->next = NULL;
	if (!head) head = aux, tail = head;
	else tail->next = aux, tail = tail->next;
}
void Pop_Front(coada &head, coada &tail)
{
	if (!head && !tail) return;
	if (head == tail)
	{
		coada aux = head;
		head = NULL, tail = head;
		delete aux;
		return;
	}
	coada aux = head;
	head = head->next;
	delete aux;
}
coada head, tail;
// -------------------// 

vector < int > arce[NMAX];

int noduri, n_arce, start_point;
int dist[NMAX];

void Read()
{
	in >> noduri >> n_arce >> start_point;
	for (int i = 1; i <= n_arce; i++)
	{
		int x, y;
		in >> x >> y;
		arce[x].push_back(y);
	}
	for (int i = 1; i <= noduri; i++)
		dist[i] = -1;
	dist[start_point] = 0;
}

void Solve()
{
	Push_Back(head, tail, start_point);
	while (!Queue_Empty(head, tail))
	{
		int nod = Queue_Front(head, tail);
		Pop_Front(head, tail);
		for (unsigned d = 0; d < arce[nod].size(); d++)
		{
			int urmator = arce[nod][d];
			if (dist[urmator] == -1)
			{
				dist[urmator] = dist[nod] + 1;
				Push_Back(head, tail, urmator);
			}
		}
	}
	for (int i = 1; i <= noduri; i++)
		out << dist[i] << " ";
}


int main()
{
	Read();
	Solve();
	return 0;
}