Cod sursa(job #2823349)

Utilizator paul911234vaida paul paul911234 Data 28 decembrie 2021 11:13:59
Problema Parcurgere DFS - componente conexe Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <vector>
#include <map>
#include <fstream>
using namespace std;

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

vector <bool> nodes(100001);
map <int, vector <int>> graphN;

void dfs(int nod, bool &cnt) {
    nodes[nod] = true;
    for (int i = 0; i < graphN[nod].size(); ++i) {
        if (nodes[graphN[nod].at(i)] == false) {
            cnt = true;
            dfs(graphN[nod].at(i), cnt);
        }
    }
}

int main() {
    int n, m;
    fin >> n >> m;
    while (m--) {
        int x, y;
        fin >> x >> y;
        graphN[x].push_back(y);
        graphN[y].push_back(x);
    }
    int related_el = 0;
    for (int i = 1; i <= n; ++i) {
        if (graphN[i].size() == 0) {
            ++related_el;
        } else {
            bool cnt = false;
            dfs(i, cnt);
            if (cnt) {
              ++related_el;
            }
        }
    }
    fout << related_el;
}