Pagini recente » Cod sursa (job #3272530) | Cod sursa (job #2943682) | Cod sursa (job #326161) | Cod sursa (job #2066270) | Cod sursa (job #2651596)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
int dfs(int u,vector<int>* g, vector<pair<int,int>> *res, vector<int> &disc, vector<int> &low,stack<pair<int,int>>& s,int p) {
static int time = 0;
int comp = 0;
int children = 0;
disc[u] = low[u] = ++time;
for (int v : g[u])
if (disc[v] == -1) {
++children;
s.push({ u,v });
comp+=dfs(v, g, res, disc, low, s, u);
low[u] = min(low[u], low[v]);
if (p==-1 && children>=2 || p != -1 && low[v] >= disc[u]) {
++comp;
pair<int, int> e;
do{
e = s.top();
s.pop();
res[comp].push_back(e);
} 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 });
}
return comp;
}
int biconnectedComponents(vector<int>* g,int n, vector<pair<int,int>> *res) {
vector<int> disc(n+1, -1);
vector<int> low(n + 1);
stack<pair<int, int>> s;
int comp = 0;
for (int i = 1;i <= n;++i)
if (disc[i] == -1) {
comp += dfs(1, g, res+comp, disc, low, s, -1);
if (s.empty()) continue;
++comp;
while (!s.empty()) {
res[comp].push_back(s.top());
s.pop();
}
}
return comp;
}
int main()
{
ifstream fin("biconex.in");
ofstream fout("biconex.out");
vector<int> *g;
int n, m;
fin >> n >> m;
g = new vector<int>[n + 1];
while (m--) {
int x, y;
fin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
vector<pair<int, int>> res[100001];
int comp=biconnectedComponents(g, n, res);
fout << comp << '\n';
for (int i = 1;i <= comp;++i) {
vector<bool> v(n + 1, false);
for (auto e : res[i]) {
if (v[e.first] == false) {
fout << e.first << ' ';
v[e.first] = true;
}
if (v[e.second] == false) {
fout << e.second << ' ';
v[e.second] = true;
}
}
fout << '\n';
}
return 0;
}