Cod sursa(job #1230758)

Utilizator daniel.amarieiDaniel Amariei daniel.amariei Data 19 septembrie 2014 11:11:57
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <queue>
#include <forward_list>
#include <bitset>
using namespace std;

#define SIZE 100001

forward_list<int>* A[SIZE]; // Adjacency lists
bitset<SIZE> V; // Visited vector
short MP[SIZE]; // Stores the size of the minimum path from START to DESTINATION

int main() 
{
	ifstream ifs("bfs.in");
	ofstream ofs("bfs.out");
	
	int n, m, s;
	
	ifs >> n >> m >> s;
	
	for (int i = 0; i < m; ++i)
	{
		int x, y;
		ifs >> x >> y;
		
		if (A[x] == 00) 
		{
			A[x] = new forward_list<int>();
		}	
		A[x]->push_front(y);
	}
	
	// Do BFS
	queue<pair<int, int> > Q;
	Q.push(make_pair(s, 0));

	while (!Q.empty()) 
	{
		pair<int, int> p = Q.front();
		V.set(p.first);
		MP[p.first] = p.second;
		
		forward_list<int>* adj_list = A[p.first];
		for (forward_list<int>::iterator it = adj_list->begin(); it != adj_list->end(); ++it) 
			if (!V.test(*it)) 
				Q.push(make_pair(*it, p.second + 1));
	}
	
	for (int i = 1; i < s; ++i) 
		ofs << (MP[i] > 0 ? MP[i] : -1) << " ";

	ofs << 0 << " ";
	
	for (int i = s+1; i < n; ++i) 
		ofs << (MP[i] > 0 ? MP[i] : -1) << " ";

	return 0;
}