Cod sursa(job #1686697)

Utilizator BrandonChris Luntraru Brandon Data 12 aprilie 2016 13:02:41
Problema Componente tare conexe Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 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], UseRmv[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();
  UseRmv[curr_node] = 2;

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

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

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

  for(auto nxt: G[node]) {
    if(UseRmv[nxt] == 0) {
      Dfs(nxt, level + 1);
      highest[node] = min(highest[node], highest[nxt]);
    }
    else if(UseRmv[nxt] == 1) {
      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(UseRmv[i]) {
      continue;
    }

    Dfs(i);
  }

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

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

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