Pagini recente » Cod sursa (job #173209) | Cod sursa (job #1003491) | Cod sursa (job #576764) | Clasament .com 2009, Runda 2 | Cod sursa (job #2002655)
#include <fstream>
#include <vector>
#include <queue>
#define INF 2e9
using namespace std;
ifstream cin("bfs.in");
ofstream cout("bfs.out");
struct edge {
edge() {
this -> linked_to = 0;
this -> next_edge = NULL;
}
int linked_to;
edge* next_edge;
};
class Graph {
public:
Graph(int n) {
this -> n = n;
this -> list.resize(n + 1);
for(int i = 1; i <= n; i ++)
list[i] = NULL;
}
void insertEdge(int x, int y) {
p_insertEdge(x, y);
}
vector< edge* > list;
private:
int n;
void p_insertEdge(int x, int y) {
edge* new_edge = new edge();
new_edge -> linked_to = y;
new_edge -> next_edge = list[x];
list[x] = new_edge;
}
};
int main() {
int n, m, s;
cin >> n >> m >> s;
Graph *g = new Graph(n);
for(int i = 1; i <= m; i ++) {
int x, y;
cin >> x >> y;
g -> insertEdge(x, y);
}
vector< int > dist(n + 1, INF);
queue< int > q;
dist[s] = 0;
q.push(s);
while(!q.empty()) {
int cur = q.front();
for(edge* i = g -> list[cur]; i != NULL; i = i -> next_edge) {
if(dist[i -> linked_to] > dist[cur] + 1) {
dist[i -> linked_to] = dist[cur] + 1;
q.push(i -> linked_to);
}
}
q.pop();
}
for(int i = 1; i <= n; i ++)
if(dist[i] != INF)
cout << dist[i] << ' ';
else
cout << "-1" << ' ';
}