Cod sursa(job #3225601)

Utilizator Fantastic_Mantudor voicu Fantastic_Man Data 18 aprilie 2024 09:15:55
Problema Componente biconexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <stack>

using namespace std;

const int NMAX = 1e5;

ifstream fin("biconex.in");
ofstream fout("biconex.out");

int in[NMAX + 1], low[NMAX + 1], T = 1;
stack<int> st;

vector<int> g[NMAX + 1];

vector<vector<int>> comps;

void dfs(int node, int par = -1) {
  in[node] = low[node] = T++;
  st.push(node);
  for (int &x : g[node])
    if (x != par) {
      if (in[x] == 0) {
        dfs(x, node);
        low[node] = min(low[node], low[x]);
        if (low[x] >= in[node]) {
          vector<int> comp;
          while (st.top() != x) {
            comp.push_back(st.top());
            st.pop();
          }
          comp.push_back(x);
          st.pop();
          comp.push_back(node);
          comps.push_back(comp);
        }
      } else
        low[node] = min(low[node], in[x]);
    }
}

int main() {
  int n, m;
  fin >> n >> m;
  for (int i = 0, x, y; i < m; i++) {
    fin >> x >> y;
    g[x].push_back(y);
    g[y].push_back(x);
  }

  for (int i = 1; i <= n; i++)
    if (!in[i])
      dfs(i);

  fout << comps.size() << '\n';
  for (vector<int> &x : comps) {
    for (int &y : x)
      fout << y << ' ';
    fout << '\n';
  }

  return 0;
}