#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
std::ifstream fin("bfs.in");
std::ofstream fout("bfs.out");
int n, m, S;
std::vector<int> L[100005];
std::queue<int> q;
int d[100005];
int main() {
int x, y;
fin >> n >> m >> S;
for (int i = 1; i <= m; i++) {
fin >> x >> y;
L[x].push_back(y);
// L[y].push_back(x);
}
for (int i = 1; i <= n; i++) {
d[i] = 100000;
}
d[S] = 0;
q.push(S);
while (!q.empty()) {
x = q.front();
q.pop();
for (int w : L[x]) {
if (d[w] > d[x] + 1) {
d[w] = d[x] + 1;
q.push(w);
}
}
std::cout << x << "\n";
}
for (int i = 1; i <= n; i++) {
fout << (d[i] == 100000 ? -1 : d[i]) << " ";
}
fout << "\n";
fout.close();
return 0;
}