Cod sursa(job #2087227)

Utilizator CronosClausCarare Claudiu CronosClaus Data 13 decembrie 2017 10:14:10
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>

using namespace std;

const int mxn = 100 * 1000 + 10;

vector< int > v[ mxn ];
bool viz[ mxn ];

int n, m;
int sol;

void dfs(int nod){
    sol++;
    stack< int > s;
    s.push( nod );
    while(!s.empty()){
        int x = s.top();
        viz[ x ] = 1;
        s.pop();
        for(auto it:v[ x ])
            if(viz[ it ] == 0)
                s.push( it );
    }
}

int main()
{
    ios_base::sync_with_stdio( false );
    cin.tie( 0 );
    ifstream cin("dfs.in");
    ofstream cout("dfs.out");
    cin>> n >> m;
    for(int i = 0, x, y; i < m; i++){
        cin>> x >> y;
        v[ x ].push_back( y );
        v[ y ].push_back( x );
    }
    for(int i = 1; i <= n; i++)
        if(viz[ i ] == 0)
            dfs( i );
    cout<< sol;
    return 0;
}