Pagini recente » Cod sursa (job #2985124) | Cod sursa (job #550241) | Cod sursa (job #768576) | Rating Ungureanu Diana-Gabriela (Diana_Gabriela) | Cod sursa (job #2462877)
#include <fstream>
#include <stack>
#include <vector>
using namespace std;
struct Node
{
vector<int> edges;
int low = -1;
int time = -1;
};
using Graph = vector<Node>;
using Edge = pair<int, int>;
vector<int> ExtractComp(Graph &g, stack<Edge> &st, int last_node)
{
vector<int> comp;
while (st.top().first != last_node) {
comp.push_back(st.top().second);
st.pop();
}
comp.push_back(st.top().first);
comp.push_back(st.top().second);
st.pop();
return comp;
}
void Dfs(Graph &g, int node, stack<Edge> &st, vector<vector<int>> &comps)
{
static int time = 0;
g[node].low = g[node].time = (time += 1);
for (const auto &next : g[node].edges) {
if (g[next].time == -1) {
st.push({node, next});
Dfs(g, next, st, comps);
g[node].low = min(g[node].low, g[next].low);
if (g[next].low >= g[node].time) {
comps.push_back(ExtractComp(g, st, node));
}
}
g[node].low = min(g[node].low, g[next].time);
}
}
vector<vector<int>> FindComps(Graph &g)
{
vector<vector<int>> comps;
for (size_t i = 0; i < g.size(); i += 1) {
if (g[i].time == -1) {
stack<Edge> st;
Dfs(g, i, st, comps);
}
}
return comps;
}
int main()
{
ifstream fin("biconex.in");
ofstream fout("biconex.out");
int nodes, edges;
fin >> nodes >> edges;
Graph graph(nodes);
for (int i = 0; i < edges; i += 1) {
int a, b;
fin >> a >> b;
graph[a - 1].edges.push_back(b - 1);
graph[b - 1].edges.push_back(a - 1);
}
auto comps = FindComps(graph);
fout << comps.size() << "\n";
for (const auto &c : comps) {
for (const auto &node : c) {
fout << node + 1 << " ";
}
fout << "\n";
}
return 0;
}