Cod sursa(job #1808142)

Utilizator DeehoroEjkoliPop Darian DeehoroEjkoli Data 17 noiembrie 2016 13:35:48
Problema BFS - Parcurgere in latime Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <cstring>
#include <queue>
#include <vector>
#define nmax 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");

queue < int > tail;

vector < int > neighbours_for[nmax];

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

bool was_here[nmax];

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

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

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;
}