Pagini recente » Profil Floriii | Cod sursa (job #859092) | Cod sursa (job #2194972) | Cod sursa (job #2718078) | Cod sursa (job #2290262)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
#define nmax 1000005
vector<int> V[nmax];
int n, m, s, dist[nmax], viz[nmax];
void citire()
{
ifstream f ("bfs.in");
f>>n>>m>>s;
for(int i=0; i<m; i++)
{
int x, y;
f>>x>>y;
V[x].push_back(y);
}
}
void initialize()
{
for(int i=0; i<=n; i++)
dist[i]=-1;
}
void bfs()
{
queue<int> q;
q.push(s);
dist[s]=0;
viz[s]=1;
int nr=1;
while(!q.empty())
{
bool ok=false;
for(auto x:V[q.front()])
if(!viz[x])
{
q.push(x);
if(dist[x]==-1)
dist[x]=nr;
ok=true;
}
if(!ok)
nr++;
q.pop();
}
}
void afisare()
{
ofstream g("bfs.out");
for(int i=1; i<=n; i++)
g<<dist[i]<<' ';
}
int main()
{
citire();
initialize();
bfs();
afisare();
return 0;
}