Cod sursa(job #1650625)

Utilizator sandupetrascoPetrasco Sandu sandupetrasco Data 11 martie 2016 19:31:22
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>

using namespace std;
ifstream cin("bfs.in");
ofstream cout("bfs.out");

bool viz[100005], V[100005];
int N, M, S, x, y, cont, rsp[100005], h[100005];

typedef struct nod{
		int info;
		nod* next;
} *lnod;
lnod A[100005];

void add(lnod &a, int x){
		lnod b = new nod;
		b->info = x;
		b->next = a;
		a = b;
}

void bfs(int i){
	viz[i] = 1;
	for(lnod t = A[i]; t; t = t->next){
		if(!V[t->info]){
			V[t->info] = 1;
			h[++cont] = t->info;
			rsp[t->info] = rsp[i] + 1;
			}
		
		}
	}
int main(){
	cont = 1;
	cin >> N >> M >> S;
	h[1] = S;
	V[S] = 1;
	for(int i = 1; i <= M; i++){
		cin >> x >> y;
		add(A[x],y);
		}
	for(int i = 1; i <= N; i++)
		if(!viz[h[i]]) bfs(h[i]);
	
	for(int i = 1; i <= N; i++){
		if(i == S) cout << 0 << " ";
			else if(rsp[i] != 0) cout << rsp[i] << " ";
				else cout << -1 << " ";
		}
	return 0;
}