Cod sursa(job #3243300)

Utilizator mihai4321Draguta Mihai mihai4321 Data 17 septembrie 2024 11:32:28
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

const int NMAX = 100001;

vector<vector<int>>G(NMAX);
bool viz[NMAX];
int n, m;

void dfs(int nod)
{
    viz[nod] = 1;
    for(auto y : G[nod])
        if(viz[y] == 0)
            dfs(y);
}

void solve()
{
    int conexe = 0;
    for(int nod = 1; nod <= n; nod++)
        if(viz[nod] == 0)
        {
            conexe++;
            dfs(nod);
        }
    g << conexe;
}

void ReadGraf()
{
    int x,y;
    f >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}
int main()
{
    ReadGraf();
    solve();
    return 0;
}