Cod sursa(job #754899)

Utilizator andreea29Iorga Andreea andreea29 Data 3 iunie 2012 22:44:46
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include<fstream>
#include<vector>
#define Nmax 100010
using namespace std;
vector <int> muchii[Nmax];

int i, n, m, s, k, p, viz[Nmax], v[Nmax], t, nivel[Nmax], x, y;

void bfs (int start)
{
	for (i=1; i<=n; ++i)
		viz[i]=0;
	k=1;
	v[k]=start;
	viz[start]=1;
	p=1;
	while (p<=k)
	{
		start=v[p++];
		for (i=0; i<muchii[start].size(); ++i)
		{
			x=muchii[start][i];
			if (viz[x]==0)
			{
				v[++k]=x;
				viz[x]=1;
				nivel[x]=nivel[start]+1;
			}
		}
	}
}

int main()
{
	ifstream f("bfs.in");
	ofstream h("bfs.out");
	f>>n>>m>>s;
	t=s;
	for (i=1; i<=m; ++i)
	{
		f>>x>>y;
		muchii[x].push_back(y);
	}
	bfs(s);
	for (i=1; i<=n; ++i)
		if (nivel[i]==0 && i!=t)
			h<<"-1"<<" ";
		else
			h<<nivel[i]<<" ";
	h<<'\n';
	return 0;
}