Cod sursa(job #2182871)

Utilizator vladsftVlad Safta vladsft Data 22 martie 2018 17:58:55
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream in("dfs.in");
ofstream out("dfs.out");
const int N = 100001;
int n, s, x, y, m;
vector <int> a[N];
bool viz[N];
void citire ()
{
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        in >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    in.close();
}
int dfs(int x)
{
    viz[x] = true;
    for (int i = 0; i < a[x].size(); i++)
    {
        int y = a[x][i];
        if (!viz[y])
        {
            dfs(y);
        }
    }
}

int main()
{
    int cnt = 0;
    citire();
    int i;
    for (i = 1; i <= n; i++)
        if (!viz[i])
        {
            cnt++;
            dfs(i);
        }
    out << cnt;
    return 0;
}