Cod sursa(job #1686767)

Utilizator BrandonChris Luntraru Brandon Data 12 aprilie 2016 13:51:30
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 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, level;

void BuildStrongComp(int end_node) {
  int curr_node;

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

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

void Dfs(int node = 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);
      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;
}