Cod sursa(job #2980601)

Utilizator cygAlexandruIvanIvan Alexandru cygAlexandruIvan Data 16 februarie 2023 17:59:05
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>

using namespace std;
const int N = 100000;

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

int viz[N+1], cnt;
vector <int> a[N+1];

void dfs(int nod)
{
    viz[nod] = 1;
    for(int i : a[nod])
        if(viz[i] == 0)
            dfs(i);
}

int main()
{
    int n, m;
    in >> n >> m;

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

    for(int i = 1; i <= n; i++)
    {
        if(viz[i] == 0){
            cnt++;
            dfs(i);
        }
    }
    out << cnt;
    in.close();
    out.close();
    return 0;
}