Cod sursa(job #1350976)

Utilizator tudoras8tudoras8 tudoras8 Data 21 februarie 2015 01:29:12
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>

#define MAXN 100001

using namespace std;

int N, M;
vector<int> G[MAXN];
stack<int> st;
int viz[MAXN], c;

void dfs(int node) {
    viz[node] = 1;
    st.push(node);
    while (!st.empty()) {
        int x = st.top();
        st.pop();
        viz[x] = 1;
        for (int a: G[x])
            if (!viz[a])
                st.push(a), viz[a] = 1;
    }
}

int main()
{
    ifstream f("dfs.in");
    ofstream g("dfs.out");

    f >> N >> M;

    for (int i = 0; i < M; i++) {
        int x, y;
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }

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

    f.close();
    g.close();

    return 0;
}