Pagini recente » Cod sursa (job #397790) | Cod sursa (job #3040198) | Diferente pentru home intre reviziile 81 si 82 | Cod sursa (job #2320544) | Cod sursa (job #2854648)
#include <iostream>
#include <vector>
#include <queue>
#define MAXN 100000
using namespace std;
struct node{
vector <int> edges;
int dist;
};
node graph[MAXN + 1];
int root;
static inline void addEdge(int a, int b) {
graph[a].edges.push_back(b);
}
queue <int> q;
void bfs(int pos) {
int i;
q.push(pos);
while ( q.size() ) {
for ( i = 0; i < graph[q.front()].edges.size(); i++ ) {
if ( graph[graph[q.front()].edges[i]].dist == 0 && graph[q.front()].edges[i] != root ) {
graph[graph[q.front()].edges[i]].dist = graph[q.front()].dist + 1;
q.push(graph[q.front()].edges[i]);
}
}
q.pop();
}
}
int main() {
FILE *fin, *fout;
fin = fopen("bfs.in", "r");
fout = fopen("bfs.out", "w");
int n, m, a, b, i;
fscanf(fin, "%d%d%d", &n, &m, &root);
for ( i = 0; i < m; i++ ) {
fscanf(fin, "%d%d", &a, &b);
addEdge(a, b);
}
bfs(root);
for ( i = 1; i <= n; i++ ) {
if ( graph[i].dist > 0 || i == root )
fprintf(fout, "%d ", graph[i].dist);
else
fprintf(fout, "-1 ");
}
fclose(fin);
fclose(fout);
return 0;
}