Pagini recente » Cod sursa (job #167231) | Cod sursa (job #2265234) | Cod sursa (job #1327295) | Cod sursa (job #2809705) | Cod sursa (job #368502)
Cod sursa(job #368502)
#include<fstream>
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,i,j;
fin>>n>>m>>s;
for(int i=1;i<=n;i++)
{
a[i]=NULL;
d[i]=-1;
}
for(;m;m--)
{
fin>>i>>j;
nod *p=new nod;
p->info=j;
p->next=a[i];
a[i]=p;
}
}
void bfs()
{
nod *st,*dr;
int k;
st=dr=new nod;
dr->info=s;
dr->next=NULL;
d[s]=0;
while(st!=NULL)
{
k=st->info;
for(nod*p=a[k];p!=NULL;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*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;
}