Cod sursa(job #3368551)

Utilizator morarescuemanueleMorarescu Emanuele morarescuemanuele Data 15 octombrie 2026 08:25:47
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

const int NMAX = 1e5;

vector<int> L[NMAX+1];
bool vis[NMAX+1];

void dfs(int node) // O(n+m)
{
    vis[node] = 1;
    for(auto vec : L[node])
    {
        if(vis[vec] == 0)
        {
            dfs(vec);
        }
    }
}

int main()
{
    ifstream fin("date.in");
    ofstream fout("date.out");

    int n, m;
    fin >> n >> m;
    
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }

    int cc = 0;
    for(int i = 1; i <= n; i++)
    {
        if(vis[i] == 0)
        {
            cc++;
            dfs(i);
        }
    }
    
    fout << cc << "\n";
    fin.close();
    fout.close();

    return 0;
}