Cod sursa(job #2889453)

Utilizator 11111theodorSebastian Theodor-Ioan 11111theodor Data 12 aprilie 2022 19:51:12
Problema Parcurgere DFS - componente conexe Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <bitset>
#include <cmath>
#include <queue>
#include <map>

using namespace std;

const int oo = 2e9;

int n, m, ans;
bool viz[100005];
vector <int> a[100005];

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

int main()
{
    ifstream fin("dfs.in");
    fin >> n >> m;
    for (int i = 1; i <= n; i++) {
        int x, y;
        fin >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    for (int i = 1; i <= n; i++) {
        if (!viz[i])
            ans += 1, dfs(i);
    }
    ofstream fout("dfs.out");
    fout << ans << '\n';
    fin.close();
    fout.close();
    return 0;
}