Pagini recente » Cod sursa (job #615260) | Cod sursa (job #332204) | Cod sursa (job #180109) | Cod sursa (job #1909431) | Cod sursa (job #2651337)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
struct ant
{
int ord, varf;
};
struct nod
{
int val;
nod *next;
};
nod *l[100001];
nod *l1[100001];
int n,m,s;
void adauga(nod *&p, int x)
{
if(p==NULL)
{
p=new nod;
p->val=x;
p->next=NULL;
}
else
{
nod *q=p;
while(q->next!=NULL)
q=q->next;
nod *w=new nod;
w->val=x;
w->next=NULL;
q->next=w;
}
}
int rezolva( int s, int f, nod *l[])
{
bool apar[100001]= {0};
queue<ant> q;
if(s==f) return 0;
if(l1[f]==NULL) return -1;
nod *p=l[s];
apar[s]=1;
while(p)
{
ant x;
x.ord=1;
x.varf=p->val;
apar[p->val]=1;
q.push(x);
p=p->next;
}
while(!q.empty())
{
ant a=q.front();
q.pop();
if(a.varf==f)
return a.ord;
else
{
nod *w=l[a.varf];
while(w)
{
if(apar[w->val]==0)
{
ant x;
x.ord=a.ord+1;
x.varf=w->val;
apar[w->val]=1;
q.push(x);
}
w=w->next;
}
}
}
return -1;
}
int main()
{
fin>>n>>m>>s;
for(int i=1; i<=m; i++)
{
int x,y;
fin>>x>>y;
if(x!=y)
{
adauga(l[x],y);
adauga(l1[y],x);
}
}
for(int i=1; i<=n; i++)
{
fout<<rezolva(s,i,l)<<' ';
}
return 0;
}