Cod sursa(job #2777190)

Utilizator rapidu36Victor Manz rapidu36 Data 22 septembrie 2021 16:07:06
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

const int N = 1e5;

int n, m;
vector<int> a[N+1];
bitset <N+1> viz;

void dfs(int x)
{
    viz[x] = 1;
    for (auto y: a[x])
    {
        if (!viz[y])
        {
            dfs(y);
        }
    }
}

int main()
{
    ifstream in("dfs.in");
    ofstream out("dfs.out");
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    int nc = 0;
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            nc++;
            dfs(i);
        }
    }
    out << nc;
    in.close();
    out.close();
    return 0;
}