Cod sursa(job #2170752)

Utilizator silvereaLKovacs Istvan silvereaL Data 15 martie 2018 09:38:59
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

const int M = 100005;

ifstream fcin("dfs.in");
ofstream fcout("dfs.out");

int main()
{
    vector<int> V[M];
    stack<int> st;
    int n, m, x, y;
    fcin >> n >> m;
    for (int i = 0; i < m; ++i)
    {
        fcin >> x >> y;
        V[x].push_back(y);
        V[y].push_back(x);
    }

    bool visited[M];
    for (int i = 1; i <= n; ++i)
        visited[i] = false;
    visited[1] = true;
    int db = 1;

    st.push(1);
    for (int s = 1; s <= n; ++s)
    {
        if (!visited[s])
        {
            st.push(s);
            visited[s] = true;
            ++db;
        }

        while (!st.empty())
        {
            int ss = st.top();
            st.pop();
            for (int i = 0; i < V[ss].size(); ++i)
                if (!visited[V[ss][i]])
                {
                    visited[V[ss][i]] = true;
                    st.push(V[ss][i]);
                }
        }
    }

    fcout << db;
}