Cod sursa(job #1686650)

Utilizator BrandonChris Luntraru Brandon Data 12 aprilie 2016 12:49:33
Problema Componente tare conexe Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>

using namespace std;

const int MaxN = 100005;

ifstream cin("ctc.in");
ofstream cout("ctc.out");

vector <int> G[MaxN], StrongCom, partial_ans;
vector <vector <int>> Ans;

int depth[MaxN], highest[MaxN];
bool used[MaxN];
int n, m;

void BuildStrongComp(int end_node) {
  partial_ans.clear();
  int curr_node = StrongCom.back();
  partial_ans.push_back(curr_node);
  StrongCom.pop_back();

  while(!StrongCom.empty() and curr_node != end_node) {
    curr_node = StrongCom.back();
    partial_ans.push_back(curr_node);
    StrongCom.pop_back();
  }

  Ans.push_back(partial_ans);
  partial_ans.clear();
}

void Dfs(int node = 1, int level = 1) {
  used[node] = true;
  depth[node] = level;
  highest[node] = level;
  StrongCom.push_back(node);

  for(auto nxt: G[node]) {
    if(!used[nxt]) {
      Dfs(nxt, level + 1);
      highest[node] = min(highest[node], highest[nxt]);
    }
    else {
      highest[node] = min(highest[node], highest[nxt]);
    }
  }

  if(highest[node] == depth[node]) {
    BuildStrongComp(node);
  }
}

int main() {
  cin >> n >> m;

  for(int i = 1; i <= m; ++i) {
    int a, b;
    cin >> a >> b;

    G[a].push_back(b);
  }

  for(int i = 1; i <= n; ++i) {
    if(used[i]) {
      continue;
    }

    Dfs(i);
  }

  cout << Ans.size() << '\n';

  for(auto ans: Ans) {
    for(auto it: ans) {
      cout << it << ' ';
    }

    cout << '\n';
  }
  return 0;
}