Cod sursa(job #3172136)

Utilizator AndreiMLCChesauan Andrei AndreiMLC Data 20 noiembrie 2023 09:28:04
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("dfs.in");
ofstream g("dfs.out");

const int NMAX = 100005;
vector<int> G[NMAX];
int viz[NMAX];

int n,m;
int ans;

stack<int>st;
void DFS(int nod)
{
    st.push(nod);
    while(!st.empty())
    {
        int curent = st.top();
        st.pop();
        for(auto it : G[curent])
        {
            if(viz[it] == 0)
            {
                viz[it]=1;
                st.push(it);
            }
        }
    }
}

int main()
{
    f >> n >> m;
    for(int i = 1;i<=m;i++)
    {
        int x,y;
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for(int i = 1;i<=n;i++)
    {
        if(!viz[i])
        {
            ans++;
            DFS(i);
        }
    }
    g << ans;
    return 0;
}