Cod sursa(job #1836528)

Utilizator hantoniusStan Antoniu hantonius Data 28 decembrie 2016 14:20:26
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <vector>
#define maxn 100002
using namespace std;

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

vector <int> g[maxn];
int viz[maxn], n, m, nr;

void read()
{
    int x, y;

    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        fin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
}

void write()
{
    fout << nr << '\n';
}

void drum(int x)
{
    vector <int>::iterator it;

    for (it = g[x].begin(); it != g[x].end(); it++)
        if (viz[*it] == 0) {
            viz[*it] = 1;
            drum(*it);
        }
}

void solve()
{
    for (int i = 1; i <= n; i++)
        if (viz[i] == 0) {
            viz[i] = 1;
            drum(i);
            nr++;
        }
}

int main()
{
    read();
    solve();
    write();
    return 0;
}