Pagini recente » Cod sursa (job #2774501) | Cod sursa (job #701796) | Cod sursa (job #2160124) | Cod sursa (job #324987) | Cod sursa (job #2651702)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
vector<int> disc;
vector<int> low;
stack<pair<int, int>> s;
int comp = 0;
int n;
void dfs(int u,vector<int>* g, vector<int> *res,int p) {
static int time = 0;
int children = 0;
disc[u] = low[u] = ++time;
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;
vector<bool> viz(n + 1, 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;
vector<bool> viz(n + 1, 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) {
for (int i = 1;i <= n;++i)
if (disc[i] == -1) {
dfs(i, g, res, -1);
}
}
int main()
{
ifstream fin("biconex.in");
ofstream fout("biconex.out");
vector<int> *g;
int m;
fin >> n >> m;
g = new vector<int>[n + 1];
disc.resize(n + 1, -1);
low.resize(n + 1);
while (m--) {
int x, y;
fin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
vector<int> res[100000];
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;
}