Pagini recente » Cod sursa (job #2972290) | Cod sursa (job #1858036) | Cod sursa (job #469847) | Cod sursa (job #1259004) | Cod sursa (job #2629537)
#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]);
}