Cod sursa(job #1806294)

Utilizator DeehoroEjkoliPop Darian DeehoroEjkoli Data 15 noiembrie 2016 08:24:50
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <cstring>
#include <queue>
#define nmax 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");

queue < int > neighbours_for[nmax], tail;

int number_vertices, number_edges, first_vertex, distance_to[nmax], x, y;

bool was_here[nmax];

void read_input() {
    fin >> number_vertices >> number_edges >> first_vertex;
    for (int i = 1; i <= number_edges; ++i) {
        fin >> x >> y;
        neighbours_for[x].push(y);
    }
}

void breadth_first_algorithm() {
    tail.push(first_vertex);
    distance_to[first_vertex] = 0;
    was_here[first_vertex] = true;
    while (!tail.empty()) {
        x = tail.front();
        tail.pop();
        while (!neighbours_for[x].empty()) {
            if (!was_here[neighbours_for[x].front()]) {
                distance_to[neighbours_for[x].front()] = distance_to[x] + 1;
                was_here[neighbours_for[x].front()] = true;
                tail.push(neighbours_for[x].front());
            }
            neighbours_for[x].pop();
        }
    }
}

void type_results() {
    for (int i = 1; i <= number_vertices; ++i)
        fout << distance_to[i] << " ";
}

int main()
{
    memset(distance_to, -1, sizeof(distance_to));
    read_input();
    breadth_first_algorithm();
    type_results();
    return 0;
}