Cod sursa(job #2783089)

Utilizator oporanu.alexAlex Oporanu oporanu.alex Data 13 octombrie 2021 19:22:26
Problema Parcurgere DFS - componente conexe Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

using namespace std;

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

class Graph{

public:
    bool vis[100005];
    int noduri, muchii;
    vector<vector<int>> adj;
    Graph(int _noduri, int _muchii): noduri(_noduri), muchii(_muchii){
        for(int i = 0; i < _noduri + 1; ++i)
            {   vector <int> temp;
                adj.push_back(temp);
            }
    }

    int get_size(){
        return adj.size();
    }

    void build(){
        for(int i = 0; i < muchii; ++i)
        {
            int x, y;
            in >> x >> y;
            adj[x].push_back(y);
            adj[y].push_back(x);
        }
    }

    int print(){
        for(int i = 1; i < noduri + 1; ++i)
        {   cout << i << ": ";
            for(int j = 0; j < adj[i].size(); ++j)
                cout << adj[i][j] << " ";
            cout << "\n";
        }

    }

    void dfs(int nod){

        //cout << nod << " ";

        vis[nod] = true;
        for(int i = 0; i < adj[nod].size(); ++i)
            if(!(vis[adj[nod][i]]))
                dfs(adj[nod][i]);
    }

    int getCconexe(){
        int cnt = 0;
        for(int i = 1; i <= noduri; ++i)
            if(!(vis[i]))
            {
                ++cnt;
                dfs(i);
            }

        return cnt;
    }
};

int main()
{   int N, M;

    in >> N >> M;

    Graph g(N, M);
    g.build();

    out << g.getCconexe();
    return 0;

}