Cod sursa(job #2886942)

Utilizator iuliavIulia Vincze iuliav Data 8 aprilie 2022 17:05:55
Problema Parcurgere DFS - componente conexe Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

const int maxim=1e5+1;
vector<int>G[maxim];
int n,m,s,d[maxim];

int VIZ()
{
    for(int i=1;i<=n;i++)
        if(d[i]==0)
            return i;
    return 0;
}

void dfs(int s)
{
    stack<int>S;
    S.push(s);
    d[s]=1;
    while(!S.empty())
    {
        int k = S.top();S.pop();
        for(auto i:G[k])
            if(d[i]==0)
            {
                d[i]=1;
                S.push(i);
            }
    }
}


int main()
{
    int x,y,ct=0;
    freopen("dfs.in","r",stdin);
	freopen("dfs.out","w",stdout);
    scanf("%d %d\n",&n,&m);
    for (int i=1;i<=m;i++)
    {
        scanf("%d %d\n",&x,&y);
        G[x].push_back(y);
        G[y].push_back(x);
    }
    while(int s=VIZ())
    {
        ct++;
        dfs(s);
    }
    printf("%d",ct);
    return 0;
}