Cod sursa(job #2659775)

Utilizator FLORENTIN-GIULIANO.DUMITRUDumitru Florentin Giuliano FLORENTIN-GIULIANO.DUMITRU Data 17 octombrie 2020 13:40:28
Problema Parcurgere DFS - componente conexe Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <list>

std::ifstream in("dfs.in");
std::ofstream out("dfs.out");

class Graf{
    int n;
    std::list <int> * ad;
public:
    Graf (int n) : n(n){
        ad = new std::list<int> [n +1];
    }
    void addEdge(int i, int j){
        ad[i].push_back(j);
        ad[j].push_back(i);
    }
    int BFS();
};

int Graf::BFS(){
    int i = 1;

    int coada[n + 1];
    bool ver[n + 1];

    for (int j = 1; j <= n ; j ++){
        ver[j] = false;
    }

    coada[0] = i;
    ver[i] = true;

    int s = 0;
    int d = 1;
    int comp = 0;
    bool run = true;

    while (run){
        run = false;
        comp ++;
        while (s < d){
            int a = coada[s];
            std::list <int> :: iterator f;
            for (f = ad[a].begin(); f != ad[a].end(); f ++){
                if (! ver[*f]){
                    coada[d] = *f;
                    ver[*f] = true;
                    d ++;
                }
            }
            s ++;
        }
        for (int i =1; i <= n ; i ++)
            if (ver[i] == false)
                {
                    coada[d] = i;
                    d ++;
                    ver[i] = true;
                    run = true;
                    break;
                }
    }
    return comp;

}

int main()
{

    int n,m;
    in >> n >> m;

    Graf graf(n);

    while (m){

        int i, j;
        in >> i >> j;
        graf.addEdge(i,j);

        m --;
    }

    out << graf.BFS();

    out.close();
    in.close();
    return 0;
}