Cod sursa(job #1202887)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 30 iunie 2014 00:29:12
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <fstream>
#include <vector>
using namespace std;

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

int n, m, x, y;
int answ;
vector<vector<int> > g;
vector<bool> ok;

void DF(int k);

int main()
{
    is >> n >> m;
    g.resize(n + 1);
    ok.resize(n + 1);
    while ( m-- )
    {
        is >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    for ( int i = 1; i <= n; ++i )
    {
        if ( ok[i] )
            continue;
        ++answ;
        DF(i);
    }
    os << answ;
    is.close();
    os.close();
    return 0;
}

void DF(int k)
{
    if ( ok[k] )
        return;
    ok[k] = true;
    for ( vector<int>::iterator it = g[k].begin();it != g[k].end(); ++it )
        DF(*it);
}