Cod sursa(job #1632000)

Utilizator y0rgEmacu Geo y0rg Data 5 martie 2016 20:49:56
Problema Parcurgere DFS - componente conexe Scor 85
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream in("dfs.in");
ofstream out("dfs.out");
int n, m, s;
vector< vector<int> > graph;
vector<bool> visited;

void dfs(int vertex);

int main()
{
    in >> n >> m;

    if (n < 1 || n > 100000 || m < 0 || m > (200000 <  n*(n + 1)/2 ? 200000 : n*(n + 1)/2))
        return 1;

    graph.resize(n);
    visited.resize(n, false);
    int x, y;

    for (int i = 0; i < m; i++) {
        in >> x >> y;
        x--;
        y--;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
    in.close();

    int counter = 0;
    for (int i = 0; i < n; i++)
        if (!visited[i]) {
            counter++;
            dfs(i);
        }

    out << counter;

    out.close();
    return 0;
}

void dfs(int vertex)
{
    if (vertex < 0 || vertex > n - 1)
        return;

    stack<int> s;
    int element, i;
    bool found;

    s.push(vertex);
    visited[vertex] = true;

    while (!s.empty()) {
        element = s.top();
        found = false;

        for (i = 0; i < graph[element].size() && !found; i++)
            if (!visited[graph[element][i]]) {
                found = true;
                s.push(graph[element][i]);
                visited[graph[element][i]] = true;
            }

        if (!found) s.pop();
    }
}