Cod sursa(job #367917)

Utilizator loginLogin Iustin Anca login Data 23 noiembrie 2009 18:52:58
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
# include <fstream>
# include <iostream>
# include <cstdlib>
using namespace std;
# define MAX 100001
struct nod {
	int info;
	nod *next;};
int n, s, d[MAX];
nod *a[MAX];

void read ()
{
	ifstream fin ("bfs.in");
	int m;
	fin>>n>>m>>s;
	for (int i=1;i<=n;i++)
	{
		a[i]=NULL;
		d[i]=-1;
	}
	for (;m;m--)
	{
		int i, j;
		fin>>i>>j;
		nod *p=new nod;
		p->info=j;
		p->next=a[i];
		a[i]=p;
	}
}

void bfs ()
{
	nod *st, *dr;
	int k;
	st=dr=new nod;
	dr->info=s;
	dr->next=NULL;
	d[s]=0;
	while (st!=NULL)
	{
		k=st->info;
		for (nod*p=a[k];p;p=p->next)
			if (d[p->info]==-1)
			{
				nod *q=new nod;
				q->info=p->info;
				p->next=NULL;
				dr->next=p;
				dr=p;
				d[p->info]=d[k]+1;
			}
		nod *t=st;
		st=st->next;
		delete t;
	}
}

			

void write ()
{
	ofstream fout ("bfs.out");
	for (int i=1;i<=n;i++)
		fout<<d[i]<<" ";
}

int main ()
{
	read ();
	bfs ();
	write ();
	return 0;
}