Cod sursa(job #2883565)

Utilizator Mihai7218Bratu Mihai-Alexandru Mihai7218 Data 1 aprilie 2022 16:51:11
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.65 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
int n, m, i, cc, j, x, y, viz[100001];
vector <vector <int> > v;
void dfs (int x)
{
    viz[x] = cc;
    for (int i = 0; i < v[x].size(); i++)
        if (viz[v[x][i]] == 0)
            dfs(v[x][i]);
}
int main()
{
    fin >> n >> m; v.resize(n+1);
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    for (i = 1; i <= n; i++)
    {
        if (viz[i] == 0)
        {
            cc++;
            dfs(i);
        }
    }
    fout << cc;
    return 0;
}