Cod sursa(job #3254449)

Utilizator BogdancxTrifan Bogdan Bogdancx Data 7 noiembrie 2024 16:42:55
Problema Parcurgere DFS - componente conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

const string file_name = "dfs";

ifstream fin(file_name + ".in");
ofstream fout(file_name + ".out");

struct Vertex {
    Vertex(int v) : val(v) {};
    bool visited = false;
    int parent;
    int val;
};

void dfs(vector<vector<Vertex>>& graph, int source)
{
    for(Vertex& v: graph[source]) {
        if(!v.visited) {
            v.visited = true;
            dfs(graph, v.val);
        }
    }
}

int main()
{
    int n, m;

    fin >> n >> m;

    vector<vector<Vertex>> graph(n + 1);

    for(int e = 0; e < m; e++)
    {
        int x, y;
        
        fin >> x >> y;

        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    int conexe = 0;

    for(int i = 1; i <= n; i++)
    {
        for(Vertex& v: graph[i])
        {
            if(!v.visited)
            {
                v.visited = true;
                dfs(graph, v.val);
                ++conexe;
            }
        }
    }

    fout << conexe;
    
    return 0;
}