Cod sursa(job #3243143)

Utilizator TghicaGhica Tudor Tghica Data 16 septembrie 2024 08:53:10
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#include <stack>
#include <vector>

#define NMAX 100000

using namespace std;

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

vector<int>edge[NMAX + 1];
stack<int>st;
vector<int>componente[NMAX + 1];
int nrComp;

int momInt[NMAX + 1], timp;

void dfs(int nod) {
  st.push(nod);
  timp++;
  momInt[nod] = timp;
  for(auto copil : edge[nod]) {
    if(momInt[copil] == 0) {
      dfs(copil);
      if(momInt[copil] > momInt[nod]) {
        nrComp++;
        while(st.top() != nod) {
          componente[nrComp].push_back(st.top());
          st.pop();
        }
      }
    }
    momInt[nod] = min(momInt[nod], momInt[copil]);
  }
}

int main() {
  int n, m, a, b;
  cin>>n>>m;
  while(m--) {
    cin>>a>>b;
    edge[a].push_back(b);
  }
  dfs(1);
  nrComp++;
  while(!st.empty()) {
    componente[nrComp].push_back(st.top());
    st.pop();
  }
  cout<<nrComp<<"\n";
  for(int i = 1; i <= nrComp; i++) {
    for(int j = 0; j < componente[i].size(); j++) {
      cout<<componente[i][j]<<" ";
    }
    cout<<"\n";
  }
  return 0;
}