Pagini recente » Cod sursa (job #2678227) | Cod sursa (job #2787509) | Cod sursa (job #3140002) | Cod sursa (job #2929700) | Cod sursa (job #3233250)
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <fstream>
using namespace std;
const int MAXN = 100000;
vector<int> adj[MAXN];
int disc[MAXN], low[MAXN], parent[MAXN];
bool visited[MAXN];
stack<pair<int, int>> st;
vector<vector<int>> biconnectedComponents;
int timeCount = 0;
void dfs(int u) {
static int time = 0;
disc[u] = low[u] = ++time;
visited[u] = true;
int children = 0;
for (int v : adj[u]) {
if (!visited[v]) {
children++;
parent[v] = u;
st.push({u, v});
dfs(v);
low[u] = min(low[u], low[v]);
if ((parent[u] == -1 && children > 1) || (parent[u] != -1 && low[v] >= disc[u])) {
vector<int> component;
while (st.top().first != u || st.top().second != v) {
component.push_back(st.top().first);
component.push_back(st.top().second);
st.pop();
}
component.push_back(st.top().first);
component.push_back(st.top().second);
st.pop();
sort(component.begin(), component.end());
component.erase(unique(component.begin(), component.end()), component.end());
biconnectedComponents.push_back(component);
}
} else if (v != parent[u] && disc[v] < disc[u]) {
low[u] = min(low[u], disc[v]);
st.push({u, v});
}
}
}
void findBiconnectedComponents(int n) {
fill(disc, disc + n, -1);
fill(low, low + n, -1);
fill(parent, parent + n, -1);
fill(visited, visited + n, false);
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i);
}
}
while (!st.empty()) {
vector<int> component;
component.push_back(st.top().first);
component.push_back(st.top().second);
st.pop();
while (!st.empty() && (component.back() == st.top().first || component.back() == st.top().second)) {
component.push_back(st.top().first);
component.push_back(st.top().second);
st.pop();
}
sort(component.begin(), component.end());
component.erase(unique(component.begin(), component.end()), component.end());
biconnectedComponents.push_back(component);
}
}
int main() {
ifstream infile("biconex.in");
ofstream outfile("biconex.out");
int N, M;
infile >> N >> M;
for (int i = 0; i < M; ++i) {
int x, y;
infile >> x >> y;
adj[x - 1].push_back(y - 1);
adj[y - 1].push_back(x - 1);
}
findBiconnectedComponents(N);
outfile << biconnectedComponents.size() << endl;
for (const auto &component : biconnectedComponents) {
for (int node : component) {
outfile << node + 1 << " ";
}
outfile << endl;
}
infile.close();
outfile.close();
return 0;
}