Cod sursa(job #2198115)

Utilizator vladisimovlad coneschi vladisimo Data 23 aprilie 2018 17:45:09
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <stdio.h>
#include <assert.h>
#include <algorithm>
#include <vector>
#include <stack>

const int MAX_N = 100000;

std::vector<int> neighbours[1 + MAX_N];
std::vector<int> neighboursT[1 + MAX_N];

bool visited[1 + MAX_N];
std::vector<int> L;

int sccCount;
std::vector<int> scc[1 + MAX_N];

/*
void dfs(const int &u) {
  std::stack<int> dfsS;
  dfsS.push(u);
  visited[u] = true;
  while (!dfsS.empty()) {
    int u = dfsS.top();
    dfsS.pop();
    if (u > 0) {
      dfsS.push(-u);
      for (int v : neighbours[u])
        if (!visited[v]) {
          dfsS.push(v);
          visited[v] = true;
        }
    } else {
      L.push_back(-u);
    }
  }
}//*/

void dfs(int u) {
  visited[u] = true;
  for (int v: neighbours[u])
    if (!visited[v])
      dfs(v);
  L.push_back(u);
}

void dfsT(const int &u) {
  std::stack<int> dfsS;
  dfsS.push(u);
  visited[u] = true;
  sccCount++;
  while (!dfsS.empty()) {
    int u = dfsS.top();
    dfsS.pop();
    scc[sccCount].push_back(u);
    for (int v : neighboursT[u])
      if (!visited[v]) {
        dfsS.push(v);
        visited[v] = true;
      }
  }
}

int main() {
  freopen("ctc.in", "r", stdin);
  freopen("ctc.out", "w", stdout);
  int n, m;
  assert(scanf("%d%d", &n, &m) == 2);
  for (int i = 1; i <= m; i++) {
    int u, v;
    assert(scanf("%d%d", &u, &v) == 2);
    neighbours[u].push_back(v);
    neighboursT[v].push_back(u);
  }
  for (int i = 1; i <= n; i++)
    std::reverse(neighbours[i].begin(), neighbours[i].end());

  for (int i = 1; i <= n; i++)
    if (!visited[i])
      dfs(i);
  for (int i = 1; i <= n; i++)
    visited[i] = false;
  std::reverse(L.begin(), L.end());
  sccCount = 0;
  for (int i : L)
    if (!visited[i])
      dfsT(i);
  printf("%d\n", sccCount);
  for (int i = 1; i <= sccCount; i++) {
    for (int j : scc[i])
      printf("%d ", j);
    printf("\n");
  }
  fclose(stdin);
  fclose(stdout);
  return 0;
}