Pagini recente » Cod sursa (job #270303) | Cod sursa (job #1060973) | Cod sursa (job #2893538) | Cod sursa (job #1860552) | Cod sursa (job #1128341)
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int MAXN = 100005;
const int INF = 0x3f3f3f3f;
int N, M, S;
int cost[MAXN];
queue<int> Q;
vector<int> G[MAXN];
void Read() {
fin >> N >> M >> S;
int a, b;
for (int i = 0; i < M; ++i) {
fin >> a >> b;
G[a].push_back(b);
}
}
void BFS(int S) {
Q.push(S);
cost[S] = 0;
do {
int node = Q.front();
Q.pop();
vector<int>::iterator it;
for (it = G[node].begin(); it != G[node].end(); ++it) {
if (cost[*it] > cost[node] + 1) {
cost[*it] = cost[node] + 1;
Q.push(*it);
}
}
}while (!Q.empty());
}
void Write() {
for (int i = 1; i <= N; ++i) {
fout << (cost[i] == INF ? -1 : cost[i]) << ' ';
}
}
int main() {
Read();
memset(cost, INF, sizeof(cost));
BFS(S);
Write();
fin.close();
fout.close();
return 0;
}