Cod sursa(job #2591075)

Utilizator pregoliStana Andrei pregoli Data 29 martie 2020 17:53:55
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>
#define newline '\n'
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
///***********************

const int NMAX = 1e5 + 3;
int n, m, s;
vector<int> graph[NMAX];
bool vis[NMAX];

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

void dfs(int node)
{
    vis[node] = true;
    for (auto nei : graph[node])
        if (!vis[nei])
            dfs(nei);
}

void solve()
{
    int ans = 0;
    for (int i = 1; i <= n; i++)
        if (!vis[i])
        {
            dfs(i);
            ans++;
        }
    fout << ans << newline;
}

int main()
{
    read();
    solve();
    fout.close();
    return 0;
}