Cod sursa(job #2786931)

Utilizator gabrielanideleaNidelea Gabriela-Andreea gabrielanidelea Data 21 octombrie 2021 23:47:52
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include<iostream>
#include<fstream>
#include<queue>
#include<vector>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");


class graf{
public:
    int N, M, S, vizitat[100001], minime[100001];
    vector<int> stocare[100001];
    queue<pair<int, int>> coada;
    void bfs(int start)
    {
        int i, d =0;
        pair<int, int> nod;
        coada.push({start, 0}); // dist de la start la el insusi e 0
        minime[start] = 0;
        vizitat[start] = 1;
        while(!coada.empty())
        {
            nod = coada.front();
            minime[nod.first] = nod.second;
            coada.pop();

            for(auto i : stocare[nod.first]) // parcurgem primele elem din pereche
                if(!vizitat[i]){
                    coada.push({i, nod.second++});
                    vizitat[i] = 1;
                }
        }

    }
    graf(){};
    void creare_graf(int N, int M, int S)
    {
        this-> N = N;
        this-> M = M;
        this-> S = S;
        for(int i = 0; i< 100001; i++)
            minime[i] = -1; //umplem tabl de dist minime cu -1
    }
    void creare_adiacente(int M)
    {
        int nod1, nod2;
        for(int i = 0; i< M; i++)
        {
            f>>nod1>>nod2;
            stocare[nod1].push_back(nod2);
        }

    }
    };
graf Gr;
int main()
{
    int N, M, S;
    f>>N>>M>>S;
    Gr.creare_graf(N, M, S);
    Gr.creare_adiacente(M);
    Gr.bfs(S);
    for(int i = 0; i<N; i++)
        g<< Gr.minime[i]<<" ";
    return 0;

}