Cod sursa(job #2120934)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 3 februarie 2018 09:49:07
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <cstdio>
#include <bitset>
#include <vector>
#include <stack>
using namespace std;

const int NMAX = 100005;
int n, m;
vector<int> g[NMAX];
bitset<NMAX> inst;
int index[NMAX], lowlink[NMAX];
int globalIndex = 1;
stack<int> st;
vector<int> comp[NMAX];
int compCount;

void read() {
  scanf("%d %d ", &n, &m);
  while (m--) {
    int x, y;
    scanf("%d %d ", &x, &y);
    g[x].push_back(y);
  }
}

void dfs(int x) {
  index[x] = lowlink[x] = ++globalIndex;
  st.push(x);
  inst[x] = 1;

  for (int y : g[x]) {
    if (!index[y]) {
      dfs(y);
      lowlink[x] = min(lowlink[x], lowlink[y]);
    } else if(inst[y]) {
      lowlink[x] = min(lowlink[x], index[y]);
    }
  }

  if (index[x] == lowlink[x]) {
    ++compCount;
    int y;
    do {
      y = st.top();
      comp[x].push_back(y);
      st.pop();
      inst[y] = 0;
    } while(y != x);
  }
}

void tarjan() {
  for (int i = 1; i <= n; i++) {
    if (!index[i])
      dfs(i);
  }
}

void print() {
  printf("%d\n", compCount);
  for (int i = 1; i <= n; i++) {
    if (comp[i].empty()) continue;
    for (int x : comp[i])
      printf("%d ", x);
    printf("\n");
  }
}

int main() {
  freopen("ctc.in", "r", stdin);
  freopen("ctc.out", "w", stdout);

  read();
  tarjan();
  print();


  return 0;
}