Cod sursa(job #1541008)

Utilizator danny794Dan Danaila danny794 Data 3 decembrie 2015 17:32:06
Problema Componente tare conexe Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.14 kb
#include <cstdio>
#include <stack>
#include <vector>

#define NMAX 100005
#define MMAX 200005
#define INF  (1 << 30)

using namespace std;

int n, m, count;
bool onStack[NMAX];
int component[NMAX], minim[NMAX], numberOfEdges[NMAX];
vector<int> children[NMAX];
pair<int, int> edges[MMAX];
vector<stack<int> > solution;
stack<int> s;

void readInput() {
  freopen("ctc.in", "r", stdin);
  freopen("ctc.out", "w", stdout);
  scanf("%d %d", &n, &m);
  for (int i = 1; i <= n; i++) {
    onStack[i] = false;
    component[i] = INF;
  }
  int a, b;
  for (int i = 0; i < m; i++) {
    scanf("%d %d", &a, &b);
    edges[i].first = a;
    edges[i].second = b;
    numberOfEdges[a]++;
  }
  for (int i = 1; i <= n; i++) {
    children[i].resize(numberOfEdges[i]);
  }
  for (int i = 0; i < m; i++) {
    int a = edges[i].first,
        b = edges[i].second;
    children[a][--numberOfEdges[a]] = b;
  }
}

void push(int index) {
  onStack[index] = true;
  component[index] = minim[index] = ++count;
  s.push(index);
//  printf("Marked %d with %d\n", index, component[index]);
}

void pop(int index) {
  solution.push_back(stack<int>());
  while (!s.empty()) {
    int top = s.top();
    if (minim[index] <= minim[top]) {
//      printf("Pop %d with %d\n", top, minim[index]);
      onStack[top] = false;
      s.pop();
      solution.back().push(top);
    } else {
      break;
    }
  }
}

void visit(int index) {
  push(index);
  for (size_t i = 0; i < children[index].size(); i++) {
    int child = children[index][i];
    if (component[child] == INF) {
      visit(child);
      minim[index] = min(minim[index], minim[child]);
    } else if (onStack[child]) {
      minim[index] = min(minim[index], minim[child]);
    }
  }
//  printf("Node %d finished with %d\n", index, minim[index]);
  if (minim[index] == component[index]) {
    pop(index);
  }
}

int main() {
  readInput();
  for (int i = 1; i <= n; i++) {
    if (component[i] == INF) {
      visit(i);
    }
  }
  printf("%d\n", (int) solution.size());
  for (size_t i = 0; i < solution.size(); i++) {
    while (!solution[i].empty()) {
      printf("%d ", solution[i].top());
      solution[i].pop();
    }
    printf("\n");
  }
  return 0;
}