Pagini recente » Monitorul de evaluare | Cod sursa (job #3170890) | Cod sursa (job #1553024) | Cod sursa (job #2048214) | Cod sursa (job #1166091)
#include <algorithm>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
const int MAX_N = 100005;
vector<int> graph[MAX_N];
int cost[MAX_N];
int main() {
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, source;
fin >> n >> m >> source;
for(int i = 1; i <= m; ++ i) {
int x, y;
fin >> x >> y;
graph[x].push_back(y);
}
queue<int> q;
for(int i = 1; i <= n; ++ i) {
cost[i] = -1;
}
cost[source] = 0;
q.push(source);
while(q.empty() == false) {
//q.front()
int node = q.front();
for(int j = 0; j < graph[node].size(); ++ j) {
if(cost[graph[node][j]] == -1) {
cost[graph[node][j]] = cost[node] + 1;
q.push(graph[node][j]);
}
}
q.pop();
}
for(int i = 1; i <= n; ++ i) {
fout << cost[i] << " ";
}
fout << "\n";
return 0;
}