Mai intai trebuie sa te autentifici.
Cod sursa(job #2247675)
Utilizator | Data | 28 septembrie 2018 21:53:03 | |
---|---|---|---|
Problema | Componente biconexe | Scor | 40 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.93 kb |
#include <fstream>
#include <stack>
#include <vector>
using namespace std;
struct Node
{
int time = 0;
int lowpoint = 0;
vector<int> edges;
};
using Graph = vector<Node>;
vector<int> ExtractComp(stack<pair<int, int>> &st, const pair<int, int> &end)
{
vector<int> comp;
while (st.top() != end) {
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<pair<int, int>> &st,
vector<vector<int>> &comps)
{
static auto time = 0;
g[node].time = g[node].lowpoint = (time += 1);
for (const auto &next : g[node].edges) {
if (g[next].time != 0) {
g[node].lowpoint = min(g[node].lowpoint, g[next].time);
continue;
}
st.push({node, next});
Dfs(g, next, st, comps);
if (g[next].lowpoint < g[node].time) {
g[node].lowpoint = g[next].lowpoint;
} else {
auto new_comp = ExtractComp(st, {node, next});
comps.push_back(new_comp);
}
}
}
vector<vector<int>> GetComps(Graph &g)
{
vector<vector<int>> comps;
for (size_t i = 0; i < g.size(); i += 1) {
if (g[i].time == 0) {
stack<pair<int, int>> 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 = GetComps(graph);
fout << comps.size() << "\n";
for (const auto &comp : comps) {
for (const auto &node : comp) {
fout << node + 1 << " ";
}
fout << "\n";
}
return 0;
}