Cod sursa(job #2087213)

Utilizator CronosClausCarare Claudiu CronosClaus Data 13 decembrie 2017 09:52:22
Problema Parcurgere DFS - componente conexe Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 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 dfs(){
    int nr = 1, i = 1, sol = 0;
    stack< int > s;
    while(nr <= n){
        for(i; i <= n && viz[ i ]; i++);
        s.push( i );
        while(!s.empty()){
            int x = s.top();
            nr++;
            viz[ x ] = 1;
            s.pop();
            for(auto it:v[ x ])
                if(viz[ it ] == 0)
                    s.push( it );
        }
        sol++;
    }
    return sol;
}

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 );
    }
    cout<< dfs();
    return 0;
}