Pagini recente » Cod sursa (job #159348) | Cod sursa (job #2455083) | Cod sursa (job #289910) | Cod sursa (job #451089) | Cod sursa (job #2634654)
#include <fstream>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int N=1e5+1;
struct nod
{
int nr;
nod *st,*dr;
};
queue<int>q;
nod *v[N];
int cost[N];
int n,m,s,x,y;
void bfs(int start)
{
memset(cost,-1,sizeof(cost));
q.push(start);
cost[start]=0;
while(!q.empty())
{
nod *p=v[q.front()];
while(p!=NULL)
{
if(cost[p->nr]==-1)
{
q.push(p->nr);
cost[p->nr]=cost[q.front()]+1;
}
p=p->st;
}
q.pop();
}
}
int main()
{
fin>>n>>m>>s;
for(int i=1;i<=m;i++)
{
fin>>x>>y;
if(v[x]==NULL)
{
v[x]=new nod;
v[x]->nr=y;
v[x]->dr=NULL;
v[x]->st=NULL;
}
else
{
nod *t=new nod;
t->nr=y;
t->dr=NULL;
v[x]->dr=t;
t->st=v[x];
v[x]=t;
}
}
bfs(s);
for(int i=1;i<=n;i++)
{
fout<<cost[i]<<" ";
}
return 0;
}