Pagini recente » Cod sursa (job #2036240) | Cod sursa (job #1706702) | Istoria paginii runda/hlo_cj_av_dintrie | Cod sursa (job #1596257) | Cod sursa (job #2247420)
#include <fstream>
#include <stack>
#include <vector>
using namespace std;
struct Node
{
int time = 0;
int lowpoint = 0;
bool on_stack = false;
vector<int> edges;
};
using Graph = vector<Node>;
vector<int> ExtractComp(Graph &g, stack<int> &st, int end_node)
{
vector<int> comp;
do {
comp.push_back(st.top());
g[st.top()].on_stack = false;
st.pop();
} while (!st.empty() && comp.back() != end_node);
return comp;
}
void Dfs(Graph &g, int node, stack<int> &st, vector<vector<int>> &comps)
{
static int time = 0;
g[node].time = g[node].lowpoint = (time += 1);
g[node].on_stack = true;
st.push(node);
for (const auto &next : g[node].edges) {
if (g[next].time == 0) {
Dfs(g, next, st, comps);
}
if (g[next].on_stack) {
g[node].lowpoint = min(g[node].lowpoint, g[next].lowpoint);
}
}
if (g[node].lowpoint >= g[node].time) {
auto new_comp = ExtractComp(g, st, node);
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<int> st;
Dfs(g, i, st, comps);
}
}
return comps;
}
int main()
{
ifstream fin("ctc.in");
ofstream fout("ctc.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);
}
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;
}