Cod sursa(job #2850277)

Utilizator CiuiGinjoveanu Dragos Ciui Data 16 februarie 2022 15:48:26
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
 
using namespace std;
 
ifstream fin("bfs.in");
ofstream fout("bfs.out");

const int MAX_SIZE = 100005;
vector<int> graph[MAX_SIZE];
int distances[MAX_SIZE];
queue<int> positions;

void BFS() {
    while (!positions.empty()) {
        int currentPeak = positions.front();
        int size = graph[currentPeak].size();
        for (int i = 0; i < size; ++i) {
            int nextPeak = graph[currentPeak][i];
            if (distances[nextPeak] == -1) {
                distances[nextPeak] = distances[currentPeak] + 1;
                positions.push(nextPeak);
            }
        }
        positions.pop();
    }
}

int main() {
    int peaks, arches, startPeak;
    fin >> peaks >> arches >> startPeak;
    for (int i = 1; i <= arches; ++i) {
        int start, end;
        fin >> start >> end;
        if (start != end) {
            graph[start].push_back(end);
        }
    }
    positions.push(startPeak);
    for (int i = 1; i <= peaks; ++i) {
        distances[i] = -1;
        if (i == startPeak) {
            distances[i] = 0;
        }
    }
    BFS();
    for (int i = 1; i <= peaks; ++i) {
        fout << distances[i] << " ";
    }
    return 0;
}

/*

 
 5 5 2
 2 3
 2 1
 4 1
 3 4
 1 5
 
 1 0 1 2 2
 
 Teste:
 exemplu:
 5 7 2
 1 2
 2 1
 2 2
 3 2
 2 5
 5 3
 4 5
 
 -> 1 0 2 -1 1
 
 5 4 1
 1 2
 2 3
 3 5
 5 4
 
 -> 0 1 2 4 3
 
 5 3 1
 1 2
 2 3
 3 5
 
 -> 0 1 2 -1 3
 
 
 5 1 1
 1 2
 
 -> 0 1 -1 -1 -1
 
 5 20 3
 1 2
 1 3
 1 4
 1 5
 2 1
 2 3
 2 4
 2 5
 3 1
 3 2
 3 4
 3 5
 4 1
 4 2
 4 3
 4 5
 5 1
 5 2
 5 3
 5 4
 
 -> 1 1 0 1 1
 
 */