Cod sursa(job #966779)

Utilizator BlackElfSpulber Iosif BlackElf Data 26 iunie 2013 16:10:33
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

int N, M, S;

ofstream out ("bfs.out");

struct Node
{
	int data;
	vector<Node*> adj;
};

vector<Node*> graph;
vector<int> steps;

void load ()
{
	ifstream in ("bfs.in");
	in >> N >> M >> S;
	
	for (int i = 0; i < N; i++)
	{
		Node *n;
		n = new Node;
		n->data = i;
		
		graph.push_back(n);
		steps[i] = -1;
	}
	
	for (int i = 0; i < M; i++)
	{
		int a, b;
		in >> a >> b;
		
		graph[a]->adj.push_back(graph[b]);
	}
	
	in.close();
}

void bfs (int start)
{
	queue<Node*> q;
	q.push(graph[start]);
	steps[start] = 0;
		
	while (!q.empty())
	{
		Node *n = q.front();
		q.pop();
		
		for (int i = 0; i < n->adj.size(); i++)
		{
			if (steps[n->adj[i]->data] == -1)
			{
				steps[n->adj[i]->data] = steps[n->data] + 1;
				q.push (n->adj[i]);
			}
		}
	}
}

void output ()
{
	for (int i = 0; i < N; i++)
		out << steps[i] << ' ';
	out << endl;
	out.close();
}

int main ()
{
	load ();
	
	bfs (S);
	
	return 0;
}