Cod sursa(job #3249469)

Utilizator PetstebPopa Petru Petsteb Data 16 octombrie 2024 16:33:15
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
// https://infoarena.ro/problema/dfs
// dfs on a undirected graph
// counting conex components

#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

const int NMAX = 1e5 + 5;

vector<int> gp[NMAX];
bool visited[NMAX];
stack<int> st;
int no_of_conex_components = 0;

void DFS(int source)
{
    st.push(source);
    visited[source] = 1;
    while (!st.empty())
    {
        int node = st.top();
        st.pop();
        for (auto next : gp[node])
        {
            if (!visited[next])
            {
                st.push(next);
                visited[next] = no_of_conex_components;
            }
        }
    }
}

int main()
{
    int n, m;
    fin >> n >> m;
    while (m--)
    {
        int x, y;
        fin >> x >> y;
        gp[x].push_back(y);
        gp[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
    {
        if (!visited[i])
        {
            no_of_conex_components++;
            DFS(i);
        }
    }
    fout << no_of_conex_components;
    return 0;
}