Cod sursa(job #966783)

Utilizator BlackElfSpulber Iosif BlackElf Data 26 iunie 2013 16:20:18
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 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 + 1;
		
		graph.push_back(n);
		steps.push_back(-1);
	}
	
	for (int i = 0; i < M; i++)
	{
		int a, b;
		in >> a >> b;
		
		graph[a-1]->adj.push_back(graph[b-1]);
	}
	
	in.close();
}

void bfs (int start)
{
	queue<Node*> q;
	q.push(graph[start-1]);
	steps[start-1] = 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] == -1)
			{
				steps[n->adj[i]->data - 1] = steps[n->data - 1] + 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);

	output();
	
	return 0;
}