Cod sursa(job #1426696)

Utilizator UPB_ShiftMyBitsUPB Mirea Avram Boaca UPB_ShiftMyBits Data 30 aprilie 2015 12:49:14
Problema Parcurgere DFS - componente conexe Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

const int MAX_N = 100001;

vector<int> G[MAX_N];
bool viz[MAX_N];

void dfs(int node) {
    stack<int> st;
    st.push(node);
    while (!st.empty()) {
        viz[node] = true;
        for (auto v : G[node]) {
            if (!viz[v]) {
                st.push(v);
                viz[v] = 1;
            }
        }
        st.pop();
    }
}

int main() {
    ifstream fin("dfs.in");
    ofstream fout("dfs.out");
    int N, M;
    fin >> N >> M;
    for (int i = 0; i < M; ++i) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    int comp = 0;
    for (int i = 1; i <= N; ++i) {
        if (!viz[i]) {
            dfs(i);
            comp++;
        }
    }

    fout << comp << endl;
    fout.clear();
    fin.close();
    return 0;
}