Cod sursa(job #1852052)

Utilizator cyber_ghSoltan Gheorghe cyber_gh Data 20 ianuarie 2017 15:19:55
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <bits/stdc++.h>

using namespace std;

typedef struct nod{
	int val;
	nod* next;
	
	
}* graf;
graf lda[1000010],p;
int N,M,rs[100010],X;
bool viz[100010];
queue <int> coada;
void add(graf &a,int x){
	graf b=new nod;
	b->val=x;
	b->next=a;
	a=b;
	
	
}

void bfs(int x){
	coada.push(x);
	viz[x]=1;
	while(!coada.empty()){
		x=coada.front();
		//cout <<x<<" ";
		for(graf v=lda[x];v!=NULL;v=v->next){
			if (!viz[v->val]){
				viz[v->val]=1;
				rs[v->val]=rs[coada.front()]+1;
				coada.push(v->val);
				
			}
		}
	coada.pop();	
	}
	
	
}

int main(){
	ifstream cin("bfs.in");
	ofstream cout("bfs.out");
	cin >>N>>M>>X;
	for(int i=1;i<=M;i++){
		int x,y;
		cin >>x>>y;
		add(lda[x],y);
		
	}
	bfs(X);
	for(int i=1;i<=N;i++)  if (!viz[i]) cout <<-1<<" ";
	else cout <<rs[i]<<" ";


return 0;
}