Cod sursa(job #338703)

Utilizator prdianaProdan Diana prdiana Data 6 august 2009 17:56:24
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <stdio.h>
#include <queue>
#include <vector>
#define MAXN 100002

using namespace std;
struct nod
{
	int nd,step;
};
nod aux;
queue<nod> q;
vector<int> g[MAXN];
bool viz[MAXN];
int rez[MAXN];
int main()
{
	freopen("bfs.in","r",stdin);
	freopen("bfs.out","w",stdout);
	
	int i,s,n,m,x,y,step = 0;

	scanf("%d%d%d",&n,&m,&s);
	
	for (i=0;i<m;i++)
	{
		scanf("%d%d",&x,&y);
		g[x].push_back(y);
	}
	aux.nd = s;
	aux.step = 0;
	q.push(aux);
	rez[s] = 0;
	viz[s] = true;
	while (!q.empty())
	{
		for (i=0;i<g[q.front().nd].size();i++)
		{
			if (!viz[g[q.front().nd][i]])
			{
				aux.nd  =g[q.front().nd][i];
				aux.step = q.front().step+1;
				q.push(aux);
				viz[g[q.front().nd][i]] = true;
				rez[g[q.front().nd][i]] = q.front().step+1;
			}
		}
		q.pop();
	}
	for (i=1;i<=n;i++)
	{
		if (rez[i] == 0 && i !=s)
		{
		printf("-1 ");
		}
		else
		{
			printf("%d ",rez[i]); 
		}
	}

	return 0;
}