Cod sursa(job #2850253)

Utilizator CiuiGinjoveanu Dragos Ciui Data 16 februarie 2022 14:24:42
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <algorithm>
#include <utility>
#include <cmath>
#include <map>
#include <deque>
#include <vector>
#include <set>
using namespace std;
 
ifstream fin("bfs.in");
ofstream fout("bfs.out");
 
const int MAX_SIZE = 1000005;
vector<int> adjacent[MAX_SIZE];
int peaks, arrows, startPoint;

void minimumWay(int endPeak) {
    int moves = 0, ok = 1;
    deque<int> currentPositions;
    currentPositions.push_back(startPoint);
    int frq[MAX_SIZE] = {0};
    frq[startPoint] = 1;
    while (ok && !currentPositions.empty()) {
        ++moves;
        int currentElement = currentPositions.back();
        int size = adjacent[currentElement].size();
        for (int i = 0; i < size; ++i) { // iteram spre toate punctele unde se poate deplasa
            if (adjacent[currentElement][i] == endPeak) { // verificam daca am ajuns la destinatie
                ok = 0;
                break;
            }
            if (frq[adjacent[currentElement][i]] == 0) {
                currentPositions.push_back(adjacent[currentElement][i]); // adaugam urmatoarea pozitie
                frq[adjacent[currentElement][i]] = 1;
            }
        }
        if (ok) {
            currentPositions.pop_front();
        }
    }
    if (ok == 0) {
        fout << moves << " ";
    } else {
        fout << -1 << " ";
    }
}

int main() {
    fin >> peaks >> arrows >> startPoint;
    for (int i = 1; i <= arrows; ++i) {
        int start, end;
        fin >> start >> end;
        if (start != end) {
            adjacent[start].push_back(end); // the adjacent list is good
        }
    }
    for (int endPeak = 1; endPeak <= peaks; ++endPeak) {
        if (endPeak == startPoint) {
            fout << 0 << " ";
        } else {
            minimumWay(endPeak);
        }
    }
}
/*

 
 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
 
 
 */