Pagini recente » Cod sursa (job #854156) | Cod sursa (job #1759123) | Cod sursa (job #2855356) | Cod sursa (job #2977842) | Cod sursa (job #1620321)
#include <stdio.h>
#include <stdlib.h>
#define NMAX 100001
typedef struct node{
int info;
struct node *next;
}node;
typedef struct qNode{
int info;
struct qNode *next;
}qNode;
node *G[NMAX];
qNode *first = NULL, *last = NULL;
int viz[NMAX], dmin[NMAX];
int empty(){
return (first == NULL && last == NULL);
}
int front(){
return first->info;
}
void push(int data){
if(last == NULL){
last = (qNode*)malloc(sizeof(qNode));
last->next = NULL;
last->info = data;
first = last;
}
else {
qNode *aux = (qNode*)malloc(sizeof(qNode));
last->next = aux;
aux->next = NULL;
aux->info = data;
last = aux;
}
}
void pop(){
if(first->next == NULL){
free(first);
first = NULL;
last = NULL;
}
else {
qNode *aux = first;
free(first);
first = aux->next;
}
}
void bfs(int start){
viz[start] = 1;
push(start);
while(!empty()){
int prec = front();
pop();
node *p = NULL;
for(p = G[prec]; p != NULL; p = p->next)
if(!viz[p->info]){
push(p->info);
viz[p->info] = 1;
dmin[p->info] = dmin[prec] + 1;
}
}
}
int main(){
int n, m, i, j, s, rbites, wbites;
FILE *fpi = freopen("bfs.in", "r", stdin);
rbites = scanf("%d %d %d", &n, &m, &s);
for(; m; m--){
rbites = scanf("%d %d", &i, &j);
if(rbites == 0)
perror("Could not read from file\n");
node *p = (node*)malloc(sizeof(node));
p->next = G[i];
p->info = j;
G[i] = p;
}
fclose(fpi);
bfs(s);
FILE *fpo = freopen("bfs.out", "w", stdout);
for(i = 1; i <= n; i++){
if(!viz[i])
wbites = printf("%d ", -1);
else
wbites = printf("%d ", dmin[i]);
if(wbites == 0)
perror("Could not write to filen\n");
}
fclose(fpo);
for(i = 1; i <= n; i++){
node *p = NULL;
for(p = G[i]; p != NULL; p = p->next)
free(p);
}
return 0;
}