Cod sursa(job #502824)

Utilizator bmaticanBogdan-Alexandru Matican bmatican Data 20 noiembrie 2010 15:38:16
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#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;
}