Cod sursa(job #2210911)

Utilizator dropsdrop source drops Data 8 iunie 2018 16:14:37
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <unordered_map>
#include <set>
#include <queue>
#include <algorithm>
#include <map>
#include <stack>
#include <vector>
#include <string>
#include <cstring>
using namespace std;

vector<int> e[100100];
vector<int> et[100100];
stack<int> order;
vector<vector<int>> sol;
vector<int> comp;
bool marked[100100];

void Dfs(int x) {
  marked[x] = true;
  for (auto y : e[x]) {
    if (!marked[y]) Dfs(y);
  }
  order.push(x);
}

void RevDfs(int x) {
  marked[x] = true;
  for (auto y : et[x]) {
    if (!marked[y]) RevDfs(y);
  }
  comp.push_back(x);
}

int main() {
  freopen("ctc.in","r",stdin);
  freopen("ctc.out","w",stdout);
  int n, m, x, y;
  scanf("%d %d", &n, &m);
  for (int i = 0; i < m; ++i) {
    scanf("%d %d", &x, &y);
    e[x].push_back(y);
    et[y].push_back(x);
  }
  for (int i = 1; i <= n; ++i) {
    if (!marked[i]) {
      Dfs(i);
    }
  }
  memset(marked, 0, sizeof(marked));
  while (!order.empty()) {
    int x = order.top();
    order.pop();
    if (!marked[x]) {
      RevDfs(x);
      sol.push_back(comp);
      comp = {};
    }
  }
  printf("%d\n", sol.size());
  for (auto a_sol : sol) {
    for (auto x : a_sol) {
      printf("%d ", x);
    }
    printf("\n");
  }
  return 0;
}