Cod sursa(job #3150247)

Utilizator KRISTY06Mateiu Ianis Cristian Vasile KRISTY06 Data 15 septembrie 2023 18:16:18
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

const int MAX_LENGTH = 100000;

vector<int> graph[MAX_LENGTH + 1];

int minDistance[MAX_LENGTH + 1];

void gen(int nodesNr, int archesNr, int currentNode, int startNode, int len) {
    for (vector<int>::iterator it = graph[currentNode].begin(); it < graph[currentNode].end(); ++it) {
        if (*it != startNode) {
            gen(nodesNr, archesNr, *it, startNode, len + 1);
            minDistance[*it] = len + 1;
        }
    }
}

int main() {
    int nodesNr, archesNr, startNode;
    fin >> nodesNr >> archesNr >> startNode;
    for (int arch = 1; arch <= archesNr; ++arch) {
        int start, end;
        fin >> start >> end;
        graph[start].push_back(end);
    }
    gen(nodesNr, archesNr, startNode, startNode, 0);
    for (int i = 1; i <= nodesNr; ++i) {
        if (minDistance[i] == 0 && i != startNode) {
            fout << "-1 ";
        } else {
            fout << minDistance[i] << ' ';
        }
    }
    return 0;
}
/*
 2 2 1
 1 2
 1 1
 =>
 0 1
 
 5 7 2
 1 2
 2 1
 2 2
 3 2
 2 5
 5 3
 4 5
 =>
 1 0 2 -1 1
 */