Cod sursa(job #3235977)

Utilizator stefan_dore_Stefan Dore stefan_dore_ Data 24 iunie 2024 18:57:09
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

const int NMAX = 100000;
bool viz[NMAX+1];
int N, M, nrCC;

vector <int> G[NMAX+1];

void citire() {
    int x, y;
    f >> N >> M;
    while(M--) {
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

void DFS(int nod) {
    viz[nod] = 1;
    for (const int &x : G[nod])
        if(!viz[x])
            DFS(x);
}

int main()
{
    citire();
    for (int i=1; i<=N; i++)
        if (!viz[i]) {
            nrCC++;
            DFS(i);
        }
    g << nrCC;
    f.close();
    g.close();
    return 0;
}