Pagini recente » Cod sursa (job #295714) | Cod sursa (job #282766) | Cod sursa (job #293351) | Cod sursa (job #117852) | Cod sursa (job #525850)
Cod sursa(job #525850)
#include <fstream>
#include <algorithm>
#define nmax 100001
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
struct nod { int inf; nod * next; } *a[nmax];
struct coada { nod *front,*back; int size;};
int n,m,s,dist[nmax];
void citire ()
{
int x,y;
nod *vf;
f>>n>>m>>s;
for (int i=1; i<=m; i++)
{
f>>x>>y;
vf=new nod;
vf->inf=y;
vf->next=a[x];
a[x]=vf;
}
f.close ();
}
void pop (coada *q)
{
nod* aux=q->front;
q->front=q->front->next;
delete aux;
(q->size)--;
}
void push (coada *q,int x)
{
nod* p=new nod;
p->inf=x;
p->next=NULL;
if (q->back==NULL ||q->front==NULL)
q->back=q->front=p;
else
{
q->back->next=p;
q->back=p;
}
(q->size)++;
}
int front (coada *q)
{
return q->front->inf;
}
bool isEmpty (coada *q)
{
return (((q->size)!=0)?false:true);
}
void bfs (int i)
{
bool viz[nmax];
coada *q=new coada;
q->front=q->back=NULL; q->size=0;
memset (viz,false,sizeof(viz));
memset (dist,-1,sizeof(dist));
push(q,i);
dist[i]=0;
viz[i]=true;
while (!isEmpty(q))
{
int varf=front (q);
pop (q);
for (nod *x=a[varf]; x!=NULL; x=x->next)
if (!viz[x->inf])
{
viz[x->inf]=true;
push(q,x->inf);
dist[x->inf]=dist[varf]+1;
}
}
}
void afisare ()
{
for (int i=1; i<=n; i++)
g<<((dist[i]==-1)?-1:dist[i])<<" ";
g.close ();
}
int main ()
{
citire ();
bfs (s);
afisare ();
return 0;
}