Cod sursa(job #2530431)

Utilizator lazarandrei13Lazar Andrei lazarandrei13 Data 24 ianuarie 2020 19:38:36
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

#define N 100005
#define M 200005

/*
1 <= N <= 100 000
0 <= M <= minim(200 000, N*(N+1)/2)
*/

int n, m, k;
vector<int>muchii [M];
bool vis[N];

void dfs(int nod) {
    vis[nod] = true;
    out << nod << ' ';
    int l = muchii[nod].size();
    for (int i = 0; i < l; i++) {
        int nodActual = muchii[nod][i];
        if (!vis[nodActual]) {
            dfs(nodActual);
        }
    }
}

int main()
{

    in >> n >> m;

    for (int i = 0; i < m; i++) {
        int x, y;
        in >> x >> y;
        muchii[x].push_back(y);
        muchii[y].push_back(x);
    }

    for (int i = 1; i <= n; i++) {
        if (!vis[i]) {
            dfs(i);
            out << '\n';
            k++;
        }
    }

    out << k;
    return 0;
}