Cod sursa(job #1378796)

Utilizator alexb97Alexandru Buhai alexb97 Data 6 martie 2015 14:25:20
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>
#include <vector>
using namespace std;

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

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

void Df(int x);

int main()
{
    is >> n >> m;
    int x,y;
    g = vector<vector<int> >(n+1);
    s = vector<bool>(n+1);
    t = vector<int>(n+1);
    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])
        {
            cnt++;
            Df(i);
        }
    }
    os << cnt << ' ';
    is.close();
    os.close();
    return 0;
}

void Df(int x)
{
    s[x] = true;
    for(vector<int>::iterator it = g[x].begin(); it != g[x].end(); ++it)
    {
        if(!s[*it])
        {
            t[*it] = x;
            Df(*it);
        }
    }
}