Cod sursa(job #1751578)

Utilizator dtoniucDaniel Toniuc dtoniuc Data 1 septembrie 2016 16:20:43
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>
#include <queue>

using namespace std;

typedef struct adjNode
{
	int identifier;
	struct adjNode *next;
}AdjNode;

typedef struct queueElem
{
	int identifier;
	int pathLength;
}QueueElem;

AdjNode** ReadAdjencyLists(int n, int m, istream &fin);
void Bfs(int s, AdjNode** adjencyLists, bool* flagVector, int* result);
void WriteResult(int n, int* result, ostream& fout);

int main()
{
	ifstream fin;
	ofstream fout;
	fout.open("bfs.out");
	fin.open("bfs.in");

	int n, m, s;
	fin >> n >> m >> s;

	AdjNode** adjencyLists =  ReadAdjencyLists(n, m, fin);

	int* result = new int[n + 1]();
	bool* flagVector = new bool[n + 1]();
	Bfs(s, adjencyLists, flagVector, result);

	for(int i = 1; i <= n; i++)
	{
		if(result[i] == 0 && i != s)
		{
			result[i] = -1;
		}
	}
	WriteResult(n, result, fout);

	fin.close();
	fout.close();
	return 0;
}

AdjNode** ReadAdjencyLists(int n, int m, istream &fin)
{
	AdjNode** adjencyLists = new AdjNode*[n + 1]();
	int x, y;

	for(int i = 1; i <= m; i++)
	{
		fin >> x >> y;

		AdjNode* newNode = new AdjNode();
		newNode->identifier = y;
		newNode->next = adjencyLists[x];
		adjencyLists[x] = newNode;
	}

	return adjencyLists;
}

void Bfs(int s, AdjNode** adjencyLists, bool* flagVector, int* result)
{
	QueueElem* start = new QueueElem();
	start->identifier = s;
	start->pathLength = 0;

	flagVector[s] = true;

	queue<QueueElem*> bfsQueue;
	bfsQueue.push(start);

	while(!bfsQueue.empty())
	{
		QueueElem* top = bfsQueue.front();
		bfsQueue.pop();
		result[top->identifier] = top->pathLength;

		AdjNode* current = adjencyLists[top->identifier];
		while(current != NULL)
		{
			if(!flagVector[current->identifier])
			{
				flagVector[current->identifier] = true;
				QueueElem* newElem = new QueueElem();
				newElem->identifier = current->identifier;
				newElem->pathLength = top->pathLength + 1;
				bfsQueue.push(newElem);
			}

			current = current->next;
		}
	}
}

void WriteResult(int n, int* result, ostream& fout)
{
	for(int i = 1; i <= n; i++)
	{
		fout << result[i] << " ";
	}
}