Pagini recente » Cod sursa (job #2073047) | Cod sursa (job #2785263) | Cod sursa (job #2005590) | Cod sursa (job #3204296) | Cod sursa (job #1940064)
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std ;
const int MAX=100005;
struct neigh
{
int node;
neigh *nxt;
neigh(int a,neigh *aux)
{
node=a;
nxt=aux;
}
};
neigh *fpoint[MAX];
neigh *lpoint[MAX];
void init (int n)
{
for (int i=1; i<=n; i++)
{
fpoint[i]=NULL;
lpoint[i]=NULL;
}
}
void add_edge(int a,int b)
{
if(fpoint[a]==NULL)
{
fpoint[a]=lpoint[a]=new neigh(b,NULL);
return ;
}
lpoint[a]->nxt=new neigh(b,NULL);
lpoint[a]=lpoint[a]->nxt;
}
vector<int> Bfs(int source,int n)
{
vector<int>dist(n+1,1<<30);
dist[source]=0;
queue<int>q;
q.push(source);
while(!q.empty())
{
int node=q.front();
q.pop();
for(neigh *aux=fpoint[node]; aux!=NULL; aux=aux->nxt)
{
if(dist[aux->node]>dist[node]+1)
{
dist[aux->node]=dist[node]+1;
q.push(aux->node) ;
}
}
}
for(auto &x: dist)
if (x==(1<<30))
x=-1;
return dist ;
}
int main()
{
freopen("bfs.in","r",stdin);
freopen("bfs.out","w",stdout);
int nodes,edges,sink;
scanf("%d%d%d",&nodes,&edges,&sink);
while (edges --)
{
int x, y ;
scanf("%d%d",&x,&y);
add_edge (x, y);
}
vector <int> Solution=Bfs(sink,nodes) ;
for(int i=1; i<(int)Solution.size(); i++)
printf("%d ",Solution[i]);
return 0 ;
}