Cod sursa(job #3269389)

Utilizator TeodorLuchianovTeo Luchianov TeodorLuchianov Data 18 ianuarie 2025 21:39:58
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

ifstream in("ctc.in");
ofstream out("ctc.out");

int const NMAX = 1e5;
vector <int> g[1 + NMAX];
int indSize = 0;
int ind[1 + NMAX];
int minReach[1 + NMAX];
int onStack[1 + NMAX];

stack <int> st;

int ansSize = 0;
vector <int> ans[1 + NMAX];

void computeTarjan(int node) {
  st.push(node);
  onStack[node] = true;
  indSize++; 
  ind[node] = indSize;
  minReach[node] = ind[node];
  for(int i = 0;i < g[node].size();i++) {
    int to = g[node][i];
    if(ind[to] == 0) {
      computeTarjan(to);
      minReach[node] = min(minReach[node], minReach[to]);
    }else if(onStack[to]){
      minReach[node] = min(minReach[node], ind[to]);
    }
  }
  if(minReach[node] == ind[node]) {
    ansSize++;
    while(st.top() != node){
      ans[ansSize].push_back(st.top());
      onStack[st.top()] = false;
      st.pop();
    }
    ans[ansSize].push_back(st.top());
    onStack[st.top()] = false;
    st.pop();
  }
}

int main() {

  int n, m;
  in >> n >> m;
  for(int i = 1;i <= m;i++) {
    int a, b;
    in >> a >> b;
    g[a].push_back(b);
  }
  for(int i = 1;i <= n;i++) {
    if(ind[i] == 0) {
      computeTarjan(i);
    }  
  }
  out << ansSize << '\n';
  for(int i = 1;i <= ansSize;i++) {
    for(int j = 0;j < ans[i].size();j++) {
      out << ans[i][j] << ' ';
    }
    out << '\n';
  }
  return 0;
}