Pagini recente » Cod sursa (job #2484907) | Cod sursa (job #2757230) | Cod sursa (job #2400410) | Cod sursa (job #1338978) | Cod sursa (job #2379910)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
void bfs(int start, int n, vector< vector< int > > lista_adiacenta)
{
vector < int > cost(n+1);
vector < int >::iterator it;
queue < int > Q;
for(it = cost.begin(); it != cost.end(); ++it)
(*it) = n+2;
cost[start] = 0;
Q.push(start);
while(!Q.empty())
{
int nodCurent = Q.front();
Q.pop();
for(auto i : lista_adiacenta[nodCurent])
{
if((cost[i] == (n + 2)))
{
cost[i] = cost[nodCurent] + 1;
Q.push(i);
}
}
}
bool ok = false;
for(auto i : cost)
if(i == n+2 && ok == true) g << "-1 ";
else if(i == n+2 && ok == false) ok = true;
else g << i << ' ';
}
int main()
{
int n, m, s, x, y;
f >> n >> m >> s;
vector < vector < int > > lista_adiacenta(n + 1);
for(int i = 0; i < m; i++)
{
f >> x >> y;
lista_adiacenta[x].push_back(y);
}
bfs(s, n, lista_adiacenta);
return 0;
}