Cod sursa(job #3005691)

Utilizator MihaiAlexDevMihai Alex MihaiAlexDev Data 17 martie 2023 10:13:00
Problema Parcurgere DFS - componente conexe Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
#include <vector>
#include <iostream>

using namespace std;

int n,m;

const int grafSize = 100000;

vector<int> graf[grafSize];
vector<bool> vizitat(grafSize);

void dfs(int nod) {
    vizitat[nod] = true;
    for(unsigned int i = 0; i < graf[nod].size(); i++) {
        int vecin = graf[nod][i];
        if(!vizitat[vecin])
            dfs(vecin);
    }
}

void read() {
    ifstream in("dfs.in");
    in >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x,y;
        in >> x >> y;
        graf[x].push_back(y);
        graf[y].push_back(x);
    }
}

int main() {
    read();
    unsigned int counter = 0;
    for(int i = 1; i <= n; i++) {
        if(!vizitat[i]) {
            counter ++;
            dfs(i);
        }
    }
    ofstream out("dfs.out");
    out << counter;
}