Cod sursa(job #2120908)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 3 februarie 2018 07:45:48
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 100005;

int n, m, cnt;
vector<int> g[NMAX], gt[NMAX], result[NMAX];
bool v[NMAX];
vector<int> st;

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

void dfs(int x) {
  v[x] = 1;
  for (int y : g[x]) {
    if (!v[y])
      dfs(y);
  }
  st.push_back(x);
}

void assign(int x, int root) {
  result[root].push_back(x);

  v[x] = 1;

  for (int y : gt[x]) {
    if(!v[y])
      assign(y, root);
  }
}

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

  memset(v, 0, sizeof v);

  reverse(st.begin(), st.end());

  for(int x: st) {
    if (!v[x]) {
      cnt++;
      assign(x, x);
    }
  }
}

void print() {
  printf("%d\n", cnt);

  for (;n; n--) {
    if (result[n].empty())
      continue;
    for (auto x : result[n])
      printf("%d ", x);
    printf("\n");
  }
}

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

  read();
  kosaraju();
  print();

  return 0;
}