Cod sursa(job #1425923)

Utilizator alex.bullzAlexandru Lilian alex.bullz Data 28 aprilie 2015 16:07:33
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>

#include "Node.h"

int g_time, scc;
std::stack<int> stack;

int min (int a, int b) { return a < b ? a : b; }
void tarjan (std::vector<Node> &graph, int index);

/*void componenteConexe (std::vector<Node> &graph) {
    for (size_t i = 0; i < graph.size(); ++i) {
        if (graph[i].discoveryTime == 0) {
            tarjan (graph, i);
        }
    }
}

void tarjan (std::vector<Node> &graph, int index) {
    graph[index].discoveryTime = graph[index].lowLink = ++g_time;
    stack.push (index);
    graph[index].inStack = true;

    auto neighbors = graph[index].neighbors;
    for (size_t i = 0; i < neighbors.size(); ++i) {
        if (graph[neighbors[i]].discoveryTime == 0) {
            tarjan (graph, neighbors[i]);
            graph[index].lowLink = min (graph[index].lowLink, graph[neighbors[i]].lowLink);
        } else if (graph[neighbors[i]].inStack) {
            graph[index].lowLink = min (graph[index].lowLink, graph[neighbors[i]].discoveryTime);
        }
    }

    if (graph[index].lowLink == graph[index].discoveryTime) {
        scc++;
        int temp = -1;
        while (temp != index) {
            temp = stack.top();
            stack.pop();
            graph[temp].inStack = false;
        }
    }
}*/

void dfs (std::vector<Node>& graph, int index) {
    graph[index].visited = true;
    auto neighbors = graph[index].neighbors;
    for (size_t i = 0; i < neighbors.size(); ++i) {
        if (graph[neighbors[i]].visited == false) {
            dfs (graph, neighbors[i]);
        }
    }
}

int main() {
    std::ifstream fin ("dfs.in");
    std::ofstream fout ("dfs.out");
    int m, n, source, dest;

    fin >> n;
    fin >> m;

    std::vector<Node> graph (n);
    for (int i = 0; i < m; ++i) {
        fin >> source;
        fin >> dest;
        graph[source - 1].neighbors.push_back (dest - 1);
    }

    //componenteConexe (graph);

    for (int i = 0; i < n; ++i) {
        if (graph[i].visited == false) {
            scc++;
            dfs(graph, i);
        }
    }

    fout << scc << "\n";
    return 0;
}