Cod sursa(job #2422304)

Utilizator test666014test test test666014 Data 18 mai 2019 13:03:42
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <iomanip>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <queue>
#include <memory>
#include <algorithm>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <cstring>
#include <functional>
using namespace std;

int n, m, ok[100100];
vector<int> g[100100];

void dfs(int x) {
    ok[x] = true;
    for (auto y : g[x]) {
        if (!ok[y]) {
            dfs(y);
        }
    }
}

int main() {
    freopen("dfs.in","r",stdin);
    freopen("dfs.out","w",stdout);
    int x, y;
    scanf("%d %d", &n, &m);
    for (int i = 0; i < m; ++i) {
        scanf("%d %d", &x, &y);
        g[x].push_back(y);
        g[y].push_back(x);
    }
    int sol = 0;
    for (int i = 1; i <= n; ++i) {
        if (!ok[i]) {
            dfs(i);
            sol++;
        }
    }
    printf("%d\n", sol);
    return 0;
}