Cod sursa(job #3263720)

Utilizator EnnBruhEne Andrei EnnBruh Data 16 decembrie 2024 11:25:59
Problema BFS - Parcurgere in latime Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#pragma optimize ("Ofast")
#pragma optimize ("inline,unroll-loops,fast-math")
#pragma target   ("avx2,bmi2,popcnt,lzcnt")

#define inFile "bfs.in"
#define outFile "bfs.out"

#define maxSize 100002
#define inf 0x3f3f3f3f
#define modulo 1000000007

typedef struct {
        int data;
        void *next;
} node;

typedef struct {
        node *head, *tail;
} lList;

bool isEmpty(lList *current) {
        return current -> head == NULL;
}

void push(lList *current, int num) {
        node *temp = malloc(sizeof( node ));
        if (temp == NULL) return ;
        temp -> data = num;
        temp -> next = NULL;

        if (current -> head == NULL) {
                current -> head = temp;
                current -> tail = temp;
        } else {
                current -> tail -> next = temp;
                current -> tail = temp;
        }
}

void pop(lList *current) {
        node *temp = current -> head;
        current -> head = current -> head -> next;
        free( temp ); temp = NULL;
}

int front(lList *current) {
        return current -> head -> data;
}

lList breadthQue;
lList adj[maxSize];
int distanceTo[maxSize];

int main( ) {
        FILE *in  = fopen(inFile, "r");
        FILE *out = fopen(outFile, "w");

        int numNodes, numEdges, startNode; fscanf(in, "%d%d%d", &numNodes, &numEdges, &startNode);

        int nodeA, nodeB;
        for (int i = 0; i < numEdges; ++i) {
                fscanf(in, "%d%d", &nodeA, &nodeB);
                push(&adj[nodeA], nodeB);
//                push(&adj[nodeB], nodeA);
        }

        distanceTo[startNode] = 1; push(&breadthQue, startNode);
        while (!isEmpty(&breadthQue)) {
                int curNode = front(&breadthQue); pop(&breadthQue);
                for (node *curNeibor = adj[curNode].head; curNeibor; curNeibor = curNeibor -> next) {
                        if (distanceTo[curNeibor -> data]) continue ;
                        distanceTo[curNeibor -> data] = distanceTo[curNode] + 1;
                        push(&breadthQue, curNeibor -> data);
                }
        }

        for (int i = 1; i <= numNodes; ++i)
                fprintf(out, "%d ", distanceTo[i] - 1);
        return 0;
}