Cod sursa(job #305690)

Utilizator undogSavu Victor Gabriel undog Data 18 aprilie 2009 12:20:44
Problema BFS - Parcurgere in latime Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <cstdio>

struct node{
	node* next;
	int id;
};

int main(){
	freopen("bfs.in","rt",stdin);
	freopen("bfs.out","wt",stdout);
	
	int m,n,s;
	node* v[100002];
	int sel[100002];
	
	scanf("%d%d%d",&n,&m,&s);
	
	int i,j;
	node* tmp;
	
	for(i=0;i<n;i++){
		v[i]=NULL;
		sel[i]=0;
	}
	
	for(i=0;i<m;i++){
		int a,b;
		scanf("%d%d",&a,&b);
		
		tmp=new node;
		tmp->id=b;
		tmp->next=v[a];
		v[a]=tmp;
	}
	
	int st[100002];
	int cost[100002];
	int stl=1,l=0;
	st[0]=s;
	cost[0]=0;
	sel[s]=1;
	
	while(l<stl){
		for(tmp=v[st[l]];tmp;tmp=tmp->next)
			if(!sel[tmp->id]){
				cost[stl]=cost[l]+1;
				st[stl++]=tmp->id;
				sel[tmp->id]=1;
			}
		l++;
	}
	int aux;
	for(i=0;i<stl-1;i++)
		for(j=i+1;j<stl;j++)
			if(st[i]>st[j]){
				aux=st[i];
				st[i]=st[j];
				st[j]=aux;
				aux=cost[i];
				cost[i]=cost[j];
				cost[j]=aux;
			}
	j=0;
	for(i=1;i<=n;i++){
		if(sel[i])
			printf("%d ",cost[j++]);
		else
			printf("-1 ");
	}
	
	return 0;
}