Cod sursa(job #3298823)

Utilizator stanrares1002@gmail.comRares Stan [email protected] Data 2 iunie 2025 10:36:10
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define ll long long
#define NMAX 100005
#define INF 1000000000
#define MOD 666013

vector<int> graf[NMAX];
bool viz[NMAX];

stack<int> s;

void DFS(int nod) {
    s.push(nod);
    viz[nod] = true;
    while (!s.empty()) {
        int nodprim = s.top();
        s.pop();
        for (int x: graf[nodprim]) {
            if (!viz[x]) {
                s.push(x);
                viz[x] = true;
            }
        }

    }
}

int main() {
    ifstream cin("dfs.in");
    ofstream cout("dfs.out");

    ios::sync_with_stdio(false), cin.tie(nullptr);
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y;
        cin >> x >> y;
        graf[x].pb(y);
        graf[y].pb(x);
    }

    int componente = 0;
    for (int i = 1; i <= n; i++) {
        if (!viz[i]) {
            componente++;
            DFS(i);
        }
    }

    cout << componente;
    return 0;
}