Cod sursa(job #367912)

Utilizator xpawnripsterge contu asta xpawnrip Data 23 noiembrie 2009 18:47:33
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include<fstream>
#include<iostream>
using namespace std;
struct nod{
	int info;
	nod *next;
};

int n,d[100001],s;

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()
{
	int k;
	nod *st, *dr;
	st=dr=new nod;
	dr ->info = s;
	dr ->next = NULL;
	d[s]=0;
	while(st)
	{
		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 *p=st;
		st=st->next;
		delete p;
	}
}
void write()
{
	ofstream fout("bfs.out");
	for(int i=1;i<=n;i++)
		fout<<d[i]<<" ";
		fout.close();
}
int main()
{
	read();
	bfs();
	write();
	return 0;
}