Cod sursa(job #1463648)

Utilizator valentin50517Vozian Valentin valentin50517 Data 21 iulie 2015 13:57:00
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>

using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

typedef struct nod{
	int key;
	nod* next;
}	*lnod;
 

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


lnod A[100010];
bool T[100010], V[100010];
int N, M, S,cod[100010],k,rs[100010],nivel;

void BFS(int i){
		T[i] = true;
		for(lnod t = A[i];t;t = t->next)
			if(!V[t->key]){
				V[t->key] = true;
				cod[++k] = t->key;
				rs[t->key] = rs[i]+1;
			}
}	

int main(){
	int x,y;
	fin >> N >> M >> S;
	for(int i = 0;i<M;i++){
		fin >> x >> y;
		add(A[x],y);
	}
	k = 1;
	cod[1] = S;
	V[S] = true;
	for(int i = 1; i <= k ;i++){
		if(!T[cod[i]]) BFS(cod[i]);
	}
	
	for(int i = 1;i<=N;i++){
		if(i == S) fout << 0; else
		if(rs[i])	fout << rs[i]; else
					fout << -1;
		fout << ' ';
	}
	return 0;
}