Cod sursa(job #3318433)

Utilizator ionlucacondreaCondrea Ion-Luca ionlucacondrea Data 28 octombrie 2025 12:35:41
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    
    ifstream fin("dfs.in");
    ofstream fout("dfs.out");
    if (!fin) return 0; 

    int N, M;
    fin >> N >> M;

    vector<vector<int>> g(N + 1);
    g.reserve(N + 1);

    for (int i = 0; i < M; ++i) {
        int x, y;
        fin >> x >> y;
        if (x >= 1 && x <= N && y >= 1 && y <= N) {
            g[x].push_back(y);
            g[y].push_back(x); 
        }
    }

    vector<char> vis(N + 1, 0);
    int comp = 0;

    
    for (int start = 1; start <= N; ++start) {
        if (vis[start]) continue;
        ++comp;
        stack<int> st;
        st.push(start);
        vis[start] = 1;

        while (!st.empty()) {
            int u = st.top(); st.pop();
            for (int v : g[u]) {
                if (!vis[v]) {
                    vis[v] = 1;
                    st.push(v);
                }
            }
        }
    }

    fout << comp << "\n";
    return 0;
}