Cod sursa(job #2120990)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 3 februarie 2018 10:41:48
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <cstdio>
#include <iostream>
#include <bitset>
#include <vector>
#include <stack>
using namespace std;

const int NMAX = 100005;
int n, m;
vector<int> g[NMAX];
int index[NMAX], lowlink[NMAX], parent[NMAX];
stack<int> st;
vector<vector<int>> comp;

void read() {
  scanf("%d %d ", &n, &m);
  while (m--) {
    int x, y;
    scanf("%d %d ", &x, &y);
    g[x].push_back(y);
    g[y].push_back(x);
  }
}

void getComponent(int x, int parent) {
  vector<int> result;
  result.push_back(parent);
  while(st.top() != x) {
    result.push_back(st.top());
    st.pop();
  }
  result.push_back(x);
  comp.push_back(result);
  st.pop();
}

void dfs(int x, int parent) {
  index[x] = index[parent] + 1;
  lowlink[x] = index[x];

  for (int y : g[x]) {
    if (y == parent) continue;

    if (index[y])
      lowlink[x] = min(lowlink[x], index[y]);

    else {
      st.push(y);
      dfs(y, x);
      lowlink[x] = min(lowlink[x], lowlink[y]);
      if (lowlink[y] >= index[x]) {
        getComponent(y, x);
      }
    }
  }
}

void solve() {
  index[0] = -1;
  for (int i = 1; i <= n; i++) {
    st.push(i);
    if (!index[i])
      dfs(i, 0);
    st.pop();
  }
}

void print() {
  printf("%d\n", comp.size());
  for (auto c : comp) {
    for (int x : c)
      printf("%d ", x);
    printf("\n");
  }
}

int main() {
  freopen("biconex.in", "r", stdin);
  freopen("biconex.out", "w", stdout);

  read();
  solve();
  print();


  return 0;
}