Cod sursa(job #2702162)

Utilizator DragosC1Dragos DragosC1 Data 3 februarie 2021 00:10:16
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;

int n;
vector<int> a[100001];
bool viz[100001];

void dfs(int x) {
    int i;
    viz[x] = 1;
    for (i = 0; i < a[x].size(); i++)
        if (!viz[a[x][i]])
            dfs(a[x][i]);
}

int main() {
    int m, i, x, y, nr = 0;

    ifstream f("dfs.in");
    f >> n >> m;
    for (i = 1; i <= m; i++) {
        f >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    f.close();

    for (i = 1; i <= n; i++)
        if (!viz[i]) {        
            dfs(i);
            nr++;
        }
    ofstream g("dfs.out");
    g << nr;
    g.close();
    return 0;
}