Cod sursa(job #1075620)

Utilizator danny794Dan Danaila danny794 Data 9 ianuarie 2014 12:20:58
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

const int NMAX = 100005;
int N, M, S;
vector<int> edges[NMAX];
queue< pair<int, int> > nodes;
int dist[NMAX];

inline void read() {
	freopen("bfs.in", "r", stdin);
	freopen("bfs.out", "w", stdout);
	scanf("%i %i %i", &N, &M, &S);
	int from, to;
	for(int i = 0; i < M; i++) {
		scanf("%i %i", &from, &to);
		edges[from].push_back(to);
	}
}

inline void solve() {
	nodes.push(make_pair(S, 0));
	while( !nodes.empty() ) {
		pair<int, int> node = nodes.front();
		nodes.pop();
		for(int i = 0; i < (int) edges[node.first].size(); i++) {
			int index = edges[node.first][i];
			if( !dist[index] && index != S ) {
				dist[index] = 1 + node.second;
				nodes.push(make_pair(index, dist[index]));
			}
		}
	}
}

void printSolution() {
	for( int i = 1; i <= N; i++ )
		if( dist[i] )
			printf("%i ", dist[i]);
		else if( i == S )
			printf("0 ");
		else
			printf("-1 ");
}

int main() {
	read();
	solve();
	printSolution();
	return 0;
}