Cod sursa(job #1600514)

Utilizator alexb97Alexandru Buhai alexb97 Data 15 februarie 2016 09:22:26
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <fstream>
#include <vector>
using namespace std;

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

int n, m;
vector<vector<int> > g;
vector<bool> s;

int cnt;
void Dfs(int x);

int main()
{
    is >> n >> m;
    g = vector<vector<int> >(n+1);
    s = vector<bool>(n+1);
    int x, y;
    for(int i = 1; i <= m; ++i)
    {
        is >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    for(int i = 1; i <= n; ++i)
    {
        if(s[i] != true)
        {
            Dfs(i);
            cnt++;
        }
    }
    os << cnt;
    is.close();
    os.close();
    return 0;
}

void Dfs(int x)
{
    s[x] = true;
    for(const auto & y: g[x])
    {
        if(s[y] != true)
        {
            Dfs(y);
        }
    }

}