Cod sursa(job #2782366)

Utilizator bananamandaoneTudor Cosmin Oanea bananamandaone Data 12 octombrie 2021 11:50:28
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

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


class graf {
private:
    int n, m, viz[100003];
    bool orientat = false;
    vector<int> h[100003];

    void dfs(int nod)
    {
        viz[nod] = 1;
        for(auto i : h[nod])
            if(!viz[i])
                dfs(i);
    }

public:
    void set_graf(int noduri, int muchii, bool Orientat)
    {
        n = noduri;
        m = muchii;
        orientat = Orientat;
    }

    void adauga_muchie(int x, int y)
    {
        if(orientat)
            h[x].push_back(y);
        else
        {
            h[x].push_back(y);
            h[y].push_back(x);
        }
    }

    void conexe()
    {
        int i, nrc;
        nrc = 0;
        for(i = 1; i <= n; i++)
            if(!viz[i])
            {
                dfs(i);
                nrc++;
            }
        fout << nrc << "\n";
    }
};

graf g;

int main()
{
    int n, m, x, y, i;

    fin >> n >> m;
    g.set_graf(n, m, false);

    for(i = 1; i <= m; i++)
    {
        fin >> x >> y;
        g.adauga_muchie(x,y);
    }
    g.conexe();

    fin.close();
    fout.close();
    return 0;
}