Cod sursa(job #1939647)

Utilizator MaligMamaliga cu smantana Malig Data 25 martie 2017 21:34:12
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;
ifstream in("dfs.in");
ofstream out("dfs.out");

const int NMax = 1e5 + 5;
typedef long long ll;
const ll inf = 1e18;

int N,M,nrComp;
bool check[NMax];
vector<int> v[NMax];
stack<int> st;

void dfs(int);

int main()
{
    in>>N>>M;
    for (int i=1;i<=M;++i) {
        int x,y;
        in>>x>>y;
        v[x].push_back(y);
        v[y].push_back(x);
    }

    for (int i=1;i<=N;++i) {
        if (check[i]) {
            continue;
        }

        ++nrComp;
        dfs(i);
    }
    out<<nrComp;

    return 0;
}

void dfs(int node) {
    st.push(node);

    while (st.size()) {
        int n = st.top();
        st.pop();

        //cout<<n<<' ';
        check[n] = true;
        for (int k=0;k < (int)v[n].size();++k) {
            int son = v[n][k];
            if (check[son]) {
                continue;
            }

            check[son] = true;
            st.push(son);
        }
    }
}