Cod sursa(job #2206015)

Utilizator georgeromanGeorge Roman georgeroman Data 20 mai 2018 20:43:51
Problema Componente tare conexe Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <algorithm>
#include <fstream>
#include <stack>
#include <vector>

std::vector<std::vector<int>> graph;
std::vector<int> index;
std::vector<int> lowlink;
int currIndex = 0;

std::vector<std::vector<int>> comps;
std::stack<int> s;

void strongConnect(int u) {
  index[u - 1] = currIndex;
  lowlink[u - 1] = currIndex;
  currIndex++;
  s.push(u);
  
  for (int v : graph[u - 1]) {
    if (index[v - 1] == -1) {
      strongConnect(v);
      lowlink[u - 1] = std::min(lowlink[v - 1], lowlink[u - 1]);
    } else {
      lowlink[u - 1] = std::min(lowlink[u - 1], index[v - 1]);
    }
  }
  
  if (index[u - 1] == lowlink[u - 1]) {
    comps.push_back(std::vector<int>());
    int curr;
    do {
      curr = s.top();
      s.pop();
      comps[comps.size() - 1].push_back(curr);
    } while (curr != u);
  }
}

int main() {
  std::ifstream in("ctc.in");
  std::ofstream out("ctc.out");
  
  int n, m;
  in >> n >> m;
  
  graph.reserve(n);
  index.reserve(n);
  lowlink.reserve(n);
  for (int i = 0; i < n; i++) {
    graph.push_back(std::vector<int>());
    index.push_back(-1);
    lowlink.push_back(-1);
  }
  
  for (int i = 0; i < m; i++) {
    int from, to;
    in >> from >> to;
    graph[from - 1].push_back(to);
  }
  
  for (int i = 1; i <= n; i++) {
    if (index[i - 1] == -1) {
      strongConnect(i);
    }
  }
  
  out << comps.size() << "\n";
  for (auto c : comps) {
    for (int u : c) {
      out << u << " ";
    }
    out << "\n";
  }
  
  return 0;
}