Cod sursa(job #972001)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 10 iulie 2013 19:39:37
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <fstream>
#include <vector>
#include <queue>

std::vector<int> bfs(std::vector<int> *l, int nV, int i)
{
	std::vector<int> nA;
	nA.resize(nV, -1);
	nA[i] = 0;
	std::queue<int> myQ;
	myQ.push(i);
	while(!myQ.empty())
	{
		int n = myQ.front();
		myQ.pop();
		for(unsigned j(0); j < l[n].size(); j++)
		{
			int m = l[n][j];
			if(nA[m] == -1) myQ.push(m), nA[m] = nA[n] + 1;
		}		
	}
	return nA;
}

int main(void)
{
	std::ofstream out("bfs.out");
	std::ifstream in("bfs.in");
	int nV, nM, k, a, b;
	in >> nV >> nM >> k;
	k--;
	std::vector<int> *l = new std::vector<int>[nV];
	for(int i(0); i < nM; i++)
	{
		in >> a >> b;
		a--;
		b--;
		l[a].push_back(b);
	}
	std::vector<int> nA = bfs(l, nV, k);
	for(unsigned i(0); i < nV; i++)
		out << nA[i] << ' ';
	return 0;
}