Cod sursa(job #3252233)

Utilizator fabeezzFabrizzio Jiglau fabeezz Data 28 octombrie 2024 21:24:52
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");

vector<vector<int>> ad;
vector<bool> viz;
int nr_cc;

void ConstrListaAd(int m)
{
    int src, dest;
    for (int i = 1; i <= m; i++)
    {
        f >> src >> dest;
        ad[src].push_back(dest);
        ad[dest].push_back(src);
    }
}

void DFS(int start)
{
    viz[start] = true;
    for (auto u : ad[start])
        if (!viz[u])
            DFS(u);
}

void CC()
{
    int n = ad.size() - 1;
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            nr_cc++;
            DFS(i);
        }
    }
}

int main()
{
    int n, m;
    f >> n >> m;

    ad.resize(n + 1);
    viz.resize(n + 1, false);

    ConstrListaAd(m);
    CC();
    g << nr_cc << "\n";

    f.close();
    g.close();
    return 0;
}