Cod sursa(job #694799)

Utilizator vitaleamaldur vitalik vitalea Data 28 februarie 2012 00:09:35
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

#define MAX 100

int n,m,S;

vector< vector <int> >arc( MAX );


int bfs( int root, int keyNode ){
	vector<int>seen( n+1 );
	queue<int>fifo;
	vector<int>cost( n+1 );
	cost[root]=0;
	fifo.push(root);
	while( !fifo.empty() ){
		int nod = fifo.front();
		if( nod == keyNode ){
			return cost[ nod ];
		}
		fifo.pop();
		seen[ nod ] = 1;
		for( int i=0; i<arc[ nod ].size(); i++ ){
			if( seen[ arc[ nod ][ i ] ] != 1 ){
				cost[ arc[ nod ][ i ] ] = cost[ nod ] + 1;
				fifo.push( arc[ nod ][ i ] );
			}
		}
	}
	seen.clear();
	cost.clear();
	return -1;
}

int main(){
	ifstream in("bfs.in");
	ofstream out("bfs.out");
	in >> n >> m >> S;
	for( int i=1; i<=m; i++ ){
		int x,y;
		in >> x >> y;
		arc[x].push_back(y);
	}
	for( int i=1; i<=n; i++ ){
		out << bfs( S, i ) << " ";
	}
	in.close();
	out.close();
	return 0;
}