Pagini recente » Cod sursa (job #2844718) | Cod sursa (job #2088354) | Cod sursa (job #1668772) | Cod sursa (job #2681897) | Cod sursa (job #2648013)
#include <iostream>
#include <fstream>
#include <vector>
#define N_MAX 100001
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
vector<string> names;
vector<int> graph[N_MAX];
int distance2[N_MAX];
bool visited[N_MAX];
int n, index = -1, start;
void read(){
int x, y, m;
f >> n >> m >> start;
for (int i=1; i<=m; i++){
f >> x >> y;
if (x!=y)
graph[x].push_back(y);
}
}
int queue1[N_MAX], lvlTop = -1, lvlBottom = -1;
void BFS(int node){
if (lvlBottom > lvlTop)
return;
lvlBottom++;
for (int i=0; i<graph[node].size(); i++)
if (visited[graph[node][i]] == false){
visited[graph[node][i]] = true;
distance2[graph[node][i]] = distance2[node] + 1;
lvlTop++;
queue1[lvlTop] = graph[node][i];
}
BFS(queue1[lvlBottom]);
}
void write(){
for (int i=1; i<=n; i++)
if (distance2[i] == 0)
if (i == start)
g << "0 ";
else
g << "-1 ";
else
g << distance2[i] << " ";
}
int main()
{
read();
visited[start] = true;
BFS(start);
write();
return 0;
}