Pagini recente » Cod sursa (job #1612097) | Cod sursa (job #1716300) | Atasamentele paginii CeiMaiMariOlimpicari: Runda #4 | Cod sursa (job #1865620) | Cod sursa (job #2303102)
#include <fstream>
#include <queue>
#include <utility>
#include <vector>
#define LGMAX 100005
#define pii pair<int,int>
#define mp make_pair
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
vector<int> g[LGMAX];
queue<pii> c;
int n, m, start;
int uz[LGMAX], cost[LGMAX];
void citire();
void bfs(int start);
int main()
{
citire();
for (int i=1; i<=n; i++)
{
cost[i] = -1;
}
bfs(start);
for (int i=1; i<=n; i++)
{
fout << cost[i] << " ";
}
fout << '\n';
return 0;
}
void citire()
{
int x, y;
fin >> n >> m >> start;
for (int i=1; i<=m; i++)
{
fin >> x >> y;
g[x].push_back(y);
}
}
void bfs(int start)
{
c.push(mp(start, 0));
uz[start] = 1;
while (!c.empty())
{
pii act = c.front();
c.pop();
cost[act.first] = act.second;
for (int i=0; i<g[act.first].size(); i++)
{
if (!uz[g[act.first][i]])
{
uz[g[act.first][i]] = 1;
c.push(mp(g[act.first][i], act.second + 1));
}
}
}
}