Pagini recente » Cod sursa (job #656884) | Cod sursa (job #1992335) | Cod sursa (job #2212358) | Cod sursa (job #1915163) | Cod sursa (job #502824)
Cod sursa(job #502824)
#include<stdio.h>
#include<stdlib.h>
#include<queue>
struct list {
int data;
struct list* next;
};
struct list* vertices[100001];
int res[100001];
int main() {
freopen("bfs.in", "r",stdin);
freopen("bfs.out", "w", stdout);
int N, M, S;
int x,y, i;
scanf("%d%d%d", &N, &M, &S);
// memset(vertices, 0, (N+1)*sizeof(struct list*));
for(i = 1; i <= N; i++) {
vertices[i] = NULL;
}
while(M--) {
scanf("%d%d", &x, &y);
struct list* cur = (struct list*)malloc(sizeof(struct list));
cur->data = y;
cur->next = vertices[x];
vertices[x] = cur;
}
for(i = 1; i <= N; i++) {
res[i] = -1;
}
std::queue<int> fifo;
fifo.push(S);
res[S] = 0;
int count = 1;
while(!fifo.empty()) {
int popped = fifo.front();
fifo.pop();
struct list* head = vertices[popped];
while(head != NULL) {
int index = head->data;
if(res[index] == -1) {
res[index] = count;
fifo.push(index);
}
head = head->next;
}
count++;
}
for(i = 1; i<= N; i++) {
printf("%d ", res[i]);
}
return 0;
}