Cod sursa(job #1802986)

Utilizator AkrielAkriel Akriel Data 10 noiembrie 2016 21:14:12
Problema BFS - Parcurgere in latime Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define N 100000

using namespace std;

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

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

node *root[N], *top[N];

int totalNodes, totalEdges, target;
vector <int> distances(N, -1);

inline void node_push(int index, int value)
{
    node *aux = new node;
    aux -> info = value;
    if ( root[index] == NULL )
    {
        root[index] = top[index] = aux;
        root[index] -> next = NULL;
    }
    else
    {
        top[index] -> next = aux;
        top[index] = aux;
        top[index] -> next = NULL;
    }
}

inline void readVariablesAndInitialize()
{
    f >> totalNodes >> totalEdges >> target;
    int x, y;
    for ( ; totalEdges ; totalEdges-- )
    {
        f >> x >> y;
        if ( x != y )
            node_push(x, y);
    }
}

inline void breadthFirst()
{
    vector <bool> visited (totalNodes, false);
    queue <int> Queue;
    int actualNode;
    int totalMoves;
    distances[target] = 0;
    Queue.push(target);
    visited[target] = true;
    while ( !Queue.empty() )
    {
        actualNode = Queue.front();
        totalMoves = distances[actualNode];
        Queue.pop();

        for ( node *it = root[actualNode]; it != NULL; it = it -> next )
        {
            if ( visited[it->info] == false )
            {
                visited[it->info] = true;
                distances[it->info] = totalMoves + 1;
                Queue.push(it->info);
            }
        }
    }
}

inline void displayAnswers()
{
    for ( int index = 1; index <= totalNodes; index++)
        g << distances[index] <<" ";
}

int main()
{
    readVariablesAndInitialize();
    breadthFirst();
    displayAnswers();
}