Pagini recente » Cod sursa (job #535560) | Cod sursa (job #163225) | Cod sursa (job #2732785) | Cod sursa (job #805914) | Cod sursa (job #2651718)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define NMAX 100005
using namespace std;
vector<int> disc;
vector<int> low;
stack<pair<int, int>> s;
vector<bool> viz;
vector<int> res[NMAX];
vector<int> g[NMAX];
int comp = 0;
int t = 0;
int n;
void dfs(int u,vector<int>* g, vector<int> *res,int p) {
int children = 0;
disc[u] = low[u] = ++t;
for (int v : g[u])
if (disc[v] == -1) {
++children;
s.push({ u,v });
dfs(v, g, res, u);
low[u] = min(low[u], low[v]);
if ((p==-1 && children>=2) || (p != -1 && low[v] >= disc[u])) {
++comp;
for (int i = 1;i <= n;++i)
viz[i] = false;
pair<int, int> e;
do{
e = s.top();
s.pop();
if (viz[e.first] == false) {
viz[e.first] = true;
res[comp].push_back(e.first);
}
if (viz[e.second] == false) {
viz[e.second] = true;
res[comp].push_back(e.second);
}
} while (e.first != u || e.second != v);
}
}
else if (v != p) {
low[u] = min(low[u], disc[v]);
if (disc[v] < disc[u])
s.push({ u,v });
}
if (p == -1 && !s.empty()) {
++comp;
for (int i = 1;i <= n;++i)
viz[i] = false;
pair<int, int> e;
while (!s.empty()) {
e = s.top();
s.pop();
if (viz[e.first] == false) {
viz[e.first] = true;
res[comp].push_back(e.first);
}
if (viz[e.second] == false) {
viz[e.second] = true;
res[comp].push_back(e.second);
}
}
}
}
void biconnectedComponents(vector<int>* g,int n, vector<int> *res) {
dfs(1, g, res, -1);
}
int main()
{
ifstream fin("biconex.in");
ofstream fout("biconex.out");
int m;
fin >> n >> m;
disc.resize(NMAX, -1);
low.resize(NMAX);
viz.resize(NMAX);
while (m--) {
int x, y;
fin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
biconnectedComponents(g, n, res);
fout << comp << '\n';
for (int i = 1;i <= comp;++i) {
for (int u : res[i]) {
fout << u << ' ';
}
fout << '\n';
}
return 0;
}