Cod sursa(job #2768974)

Utilizator flibiaVisanu Cristian flibia Data 12 august 2021 21:28:14
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>

using namespace std;

struct Node {
    int val; 
    Node *next;
};

void push(Node **x, int v) {
    if (x == nullptr) {
        *x = new Node{v, nullptr};
        return;
    }

    Node *aux = new Node{v, *x};
    *x = aux;
}

const int N = 1e5 + 10;

int n, m;
Node *v[N];
int viz[N];

void dfs(int x) {
    viz[x] = 1;
    for (auto it = v[x]; it != nullptr; it = it->next) {
        if (!viz[it->val]) {
            dfs(it->val);
        }
    }
}

int main() {
    ifstream cin("dfs.in");
    ofstream cout("dfs.out");
    
    cin >> n >> m;
    for (int i = 1, x, y; i <= m; i++) {
        cin >> x >> y;
        push(&v[x], y);
        push(&v[y], x);
    }

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

    cout << ans;
    
    return 0;
}