Cod sursa(job #2019124)

Utilizator mihailarminia1234Arminia Mihail mihailarminia1234 Data 7 septembrie 2017 09:16:40
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <iostream>

using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

struct el
{
        int info;
        el *next;
};

el *nods[100005], *p, *q;
el *head, *curent, *another;
int distanta[100005], n, m, s, nodX, nodY, pas;

void Adauga_Vecin(int x, int y)
{
        q = new el;
        q -> info = y;
        q -> next = nods[x];
        nods[x] = q;
}

void Adauga_inCoada(int nod)
{
        another = new el;
        another -> info = nod;
        another -> next = NULL;
        curent -> next = another;
        curent = another;
}

void Pop()
{
        el *aux;
        aux = head;
        head = head -> next;
        delete aux;
}

void BFS()
{
        while(head != NULL)
        {
                int nodcurent = head -> info;
                for(p = nods[nodcurent]; p != NULL; p = p -> next)
                {
                        if(distanta[p -> info] == -1)
                        {
                                Adauga_inCoada(p -> info);
                                distanta[p -> info] = distanta[nodcurent] + 1;
                        }
                }
                Pop();
        }
}

int main()
{
        f >> n >> m >> s;
        for(int i = 1; i <= m; ++i)
        {
                f >> nodX >> nodY;
                if(nodX != nodY) Adauga_Vecin(nodX, nodY);
        }
        for(int i = 1; i <= n; ++i) distanta[i] = -1;
        distanta[s] = 0;
        head = new el;
        head -> info = s;
        head -> next = NULL;
        curent = head;
        BFS();
        for(int i = 1; i <= n; ++i) g << distanta[i] << " ";
        return 0;
}