Cod sursa(job #796945)

Utilizator mihaibogdan10Mihai Bogdan mihaibogdan10 Data 13 octombrie 2012 00:26:59
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.67 kb
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
ifstream fin("bfs.in"); ofstream fout("bfs.out");

vector <int> G[100001];
int niv[100001], top, N, M, s;
bool viz[100001];
queue<int> q;

void BFS(){
	int i, v, adj;
	q.push(s), viz[s] = true;
	
	while (!q.empty()){
		v = q.front(), q.pop();
		for (i = 0; i < G[v].size() && (adj = G[v][i]); i++)
			if (!viz[adj]){
				q.push(adj);
				viz[adj] = true;
				niv[adj] = niv[v] + 1;
			}
	}
}

int main(){
	int i, x, y;
	
	fin >> N >> M >> s;
	for (i = 0 ; i < M; i++){
		fin >> x >> y;
		G[x].push_back(y);
	}
	
	BFS();
	for (i = 1; i <= N; i++)
		fout << (i != s && niv[i] == 0 ? -1 : niv[i]) << " ";
}