Pagini recente » Cod sursa (job #1115303) | Cod sursa (job #1064625) | Cod sursa (job #2988481) | Cod sursa (job #1439993) | Cod sursa (job #2321215)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#define MAXN 100005
#define inf 0x3f3f3f3f
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
queue <int> Q;
vector <int> graph[MAXN];
int cost[MAXN];
inline void Read(int &N, int &M, int &S) {
int x, y;
fin >> N >> M >> S;
for (int i = 1; i <= M; i++) {
fin >> x >> y;
graph[x].push_back(y);
}
}
inline void BFS(int node) {
int z;
memset(cost, inf, sizeof(cost));
Q.push(node); cost[node] = 0;
while (!Q.empty()) {
z = Q.front();
for (auto x : graph[z]) {
if (cost[x] > cost[z] + 1) {
cost[x] = cost[z] + 1;
Q.push(x);
}
}
Q.pop();
}
}
inline void Write(int N) {
for (int i = 1; i <= N; i++) {
if (cost[i] == inf)
cost[i] = -1;
fout << cost[i] << " ";
}
}
int main () {
int N, M, S;
Read(N, M, S);
BFS(S);
Write(N);
fin.close(); fout.close(); return 0;
}