Cod sursa(job #2247707)

Utilizator algebristulFilip Berila algebristul Data 28 septembrie 2018 22:59:03
Problema Componente tare conexe Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;

const int kNmax = 1e5+5;

int n, m;
vector<int> g[kNmax];
int lowlink[kNmax];
int self[kNmax];

vector<int> cc[kNmax];
int cc_of_node[kNmax];

int cnt = 1;
int current = 1;
int seen[kNmax];
vector<int> seen_stack;

void tarjan(int x) {
  lowlink[x] = self[x] = current;
  seen[x] = true;
  seen_stack.push_back(x);
  current++;
  
  for (int y : g[x]) {
    if (!self[y]) {
      tarjan(y);
      lowlink[x] = min(lowlink[x], lowlink[y]);
    } else if (seen[y]) lowlink[x] = min(lowlink[x], lowlink[y]);
  }
  
  if (self[x] == lowlink[x]) {
    int node;
    do {
      node = seen_stack.back();
      cc_of_node[node] = cnt;
      cc[cnt].push_back(node);
      seen_stack.pop_back();
      seen[node] = false;
    } while (node != x);
    cnt++;
  }
}

int main() {
  #ifdef INFOARENA
  freopen("ctc.in", "r", stdin);
  freopen("ctc.out", "w", stdout);
  #endif
  
  cin >> n >> m;
  for (int x, y, i = 1; i <= m; i++) {
    cin >> x >> y;
    g[x].push_back(y);
  }
  
  for (int i = 1; i <= n; i++) {
    if (self[i]) continue;
    tarjan(i);
  }
  
  --cnt;
  
  cout << cnt << '\n';
  for (int i = 1; i <= cnt; i++) {
    for (int node : cc[i])
      cout << node << ' ';
    cout << '\n';
  }
  
  return 0;
}