Cod sursa(job #363768)

Utilizator andreitheo87Teodorescu Andrei-Marius andreitheo87 Data 14 noiembrie 2009 17:37:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include<fstream>
#include<iostream>
#include<queue>
using  namespace std;
struct node{
    int vec;
    node* next;
};
node* vec[100000];
int n,m,st;
int main()
{
	freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
	scanf("%d %d %d",&n,&m,&st);
	st--;
	memset(vec,0,sizeof(vec));
	int viz[100000];
	memset(viz,0,sizeof(viz));
	for(int i=0; i<m; i++)
	{
		int x,y;
		scanf("%d %d",&x,&y);
		x--; y--;
		node* nod = new node;
		nod->vec = y;
		nod->next = vec[x];
		vec[x] = nod;
	}
	int rez[100000];
	for(int i=0; i<n ;i++) rez[i] = -1;
	queue<int> q;
	q.push(st);
	rez[st] = 0;
    while( q.size() )
    {
        int next = q.front();
        q.pop();
        node* p = vec[next];
        while( p ){
                if( rez[p->vec] == -1 )
                {
                    rez[p->vec] = rez[next] + 1;
                    q.push(p->vec);
                }
                p = p->next;
        }
    }
    for(int i=0; i<n; i++)
        printf("%d ",rez[i]);
    printf("\n");
	return 0;
}