Cod sursa(job #2792653)

Utilizator MihaiLazar26Lazar Mihai MihaiLazar26 Data 2 noiembrie 2021 09:28:47
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

#define NMAX 100001
#define MMAX 1000005

class Graf{
    vector<int> nod[NMAX];
    vector<int> viz;
    int nrNoduri, nrMuchi;
    bool orientat = false, neorientat = false;

    void setOrientat(bool orientat = true){
        if(orientat) this->orientat = true, this->neorientat = false;
        else this->orientat = false, this->neorientat = true;
    }

    void setNeorientat(bool neorientat = true){
        if(neorientat) this->neorientat = true, this->orientat = false;
        else this->neorientat = false, this->orientat = true;
    }

    void setViz(int nod, int val){
        this->viz.assign(nod + 1, val);
    }
public:

    void citire(int nrNoduri, int nrMuchi, vector<pair<int, int>> muchi, bool orientat = true){
        if(orientat) setOrientat();
        else setNeorientat();
        this->nrNoduri = nrNoduri;
        this->nrMuchi = nrMuchi;
        for(auto i : muchi){
            this->nod[i.first].push_back(i.second);
            if(this->neorientat) this->nod[i.second].push_back(i.first);

        }
    }

    void actBFS(int S, int dist);
    vector<int> BFS(int S);

};
void Graf::actBFS(int S, int dist){
    this->viz[S] = dist;
    for(auto vecin : this->nod[S]){
        if(this->viz[vecin] == -1) actBFS(vecin, dist+1);
    }
}

vector<int> Graf::BFS(int S){
    setViz(this->nrNoduri, -1);
    actBFS(S, 0);
    return this->viz;
}

Graf graf;
void rezolvareBFS(){
    vector<pair<int, int>> muchi;
    int n, m, s;
    fin>>n>>m>>s;
    for(int i = 1; i <= m; i++){
        int x, y;
        fin>>x>>y;
        muchi.push_back(make_pair(x, y));
    }
    graf.citire(n, m, muchi);
    vector<int> sol = graf.BFS(s);
    for(int i = 1; i <= n; i++){
        fout<<sol[i]<<" ";
    }
}

int main(){
    rezolvareBFS();
}