Pagini recente » Cod sursa (job #1658964) | Monitorul de evaluare | Cod sursa (job #565645) | Cod sursa (job #1530830) | Cod sursa (job #367914)
Cod sursa(job #367914)
#include<fstream>
#include<cstdlib>
using namespace std;
#define MAX 100001
struct nod{int info;
nod *next;};
nod * a[MAX];
int n,d[MAX],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;
q->next=NULL;
dr->next=q;
dr=q;
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]<<" ";
fout.close();
}
int main()
{
read();
bfs();
write();
return 0;
}