Cod sursa(job #2494230)

Utilizator natrovanCeval Marius natrovan Data 17 noiembrie 2019 16:22:37
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <iterator>

using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");

list<int>graph[100010];
bool marked[100010];
int x, y, n, m, connectedComponents;

void DFS(int node){
    marked[node] = true;
    for(list<int>::iterator it = graph[node].begin(); it != graph[node].end(); it++)
        if(!marked[*it])
            DFS(*it);
}

int main()
{
    fin >> n >> m;

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

    for(int i = 1; i <= n; i++){
        if(!marked[i]){
            DFS(i);
            connectedComponents++;
        }
    }

    fout << connectedComponents;

    return 0;
}