Cod sursa(job #2120905)

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

const int NMAX = 100005;

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

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

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

void assign(int x, int root) {
  if (v[x]) return;
  v[x] = 1;
  result[root].push_back(x);
  for (int y: g[x]) {
    if(!v[y])
      assign(y, root);
  }
}

void kosaraju() {
  for (int i = 1; i <= n; i++) {
    dfs(i);
  }

  memset(v, 0, sizeof v);

  while(!st.empty()) {
    int x = st.top();
    st.pop();
    if (!v[x]) {
      assign(x, x);
      cnt++;
    }
  }
}

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

  for (auto it: result) {
    for (auto x: it.second)
      printf("%d ", x);
    printf("\n");
  }
}

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

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

  return 0;
}