Cod sursa(job #1242155)

Utilizator sperantaVio Alexa speranta Data 14 octombrie 2014 00:02:54
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>
#include <vector>

using namespace std;

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

vector<bool> V;
vector<vector<int>> G;
int n, m, x, y, sol;

void DFS(int i);

int main()
{
    is >> n >> m;

    G = vector<vector<int>>(n+1);
    V = vector<bool>(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 ( !V[i] )
        {
            sol++;
            DFS(i);
        }
    os << sol;
    is.close();
    os.close();
    return 0;
}

void DFS( int i )
{
    V[i] = true;
    for ( vector<int>::iterator it = G[i].begin(); it != G[i].end(); ++it )
        if ( !V[*it] )
            DFS(*it);
}