Cod sursa(job #2629537)

Utilizator RaduQQTCucuta Radu RaduQQT Data 21 iunie 2020 14:18:07
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>





typedef struct listNode
{
	listNode* next;
	int el;
};

listNode* list[100000];

void insertNodeInList(listNode*& head, int el)
{
	listNode* node = (listNode*)malloc(sizeof(listNode));
	node->el = el;

	if (head == NULL)
	{
		head = node;
		head->next = NULL;
		return;
	}

	node->next = head;
	head = node;
}

void push(listNode*& start, listNode*& finish,int el)
{
	listNode* node = (listNode*)malloc(sizeof(listNode));
	node->el = el;

	if (start == NULL)
	{
		start = node;
		finish = node;
		finish->next = NULL;
		return;
	}
	finish->next = node;
	node->next = NULL;
	finish = finish->next;
}
void pop(listNode*& start, listNode*& finish)
{
	if (start == NULL)
		return;

	if (start->next == NULL)
		finish = NULL;
	listNode* aux = start;
	start = start->next;
	free(aux);
}
int n, m,rad;

int dist[100000];
bool viz[100000];

void bfs(listNode* start, listNode* finish)
{
	if (start == NULL)
		return;
	listNode* aux = list[start->el];
	int anterior = start->el;
	viz[anterior] = 1;

	pop(start, finish);
	while (aux != NULL)
	{
		if (aux->el == anterior)
			dist[aux->el] = dist[anterior];
		if (!viz[aux->el])
		{
			dist[aux->el] = dist[anterior] + 1;
			push(start, finish, aux->el);
		}
		aux = aux->next;
	}
	bfs(start, finish);
}
int main()
{
	freopen("bfs.in", "r", stdin);
	freopen("bfs.out", "w", stdout);

	scanf("%d%d%d", &n, &m, &rad);
	for (int i = 1; i <= n; i++)
		list[i] = NULL;

	int a, b;
	for (int i = 0; i < m; i++)
	{
		scanf("%d%d", &a, &b);
		insertNodeInList(list[a], b);
	}


	for (int i = 1; i <= n; i++)
		dist[i] = -1;
	dist[rad] = 0;


	listNode* start = NULL, *finish = NULL;
	push(start, finish, rad);
	bfs(start, finish);
	for (int i = 1; i <= n; i++)
		printf("%d ", dist[i]);
}