Cod sursa(job #1632155)

Utilizator mariapascuMaria Pascu mariapascu Data 5 martie 2016 22:04:38
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.7 kb
#include <fstream>
#include <vector>
using namespace std;

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

int n, m, nrc;
vector<vector<int>> G;
vector<bool> s;

void Read();
void DFS(int x);

int main() {
    Read();
    for (int i = 1; i <= n; i++)
        if (!s[i]) nrc++, DFS(i);
    fout << nrc;
    fin.close();
    fout.close();
    return 0;
}

void DFS(int x) {
    s[x] = true;
    for (const int & e : G[x])
    if (!s[e]) DFS(e);
}

void Read() {
    fin >> n >> m;
    G = vector<vector<int>>(n + 1);
    s = vector<bool>(n + 1);
    for (int i = 0, x, y; i < m; i++) {
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}