Pagini recente » Cod sursa (job #2287505) | Cod sursa (job #1597507) | Cod sursa (job #145142) | Cod sursa (job #1756822) | Cod sursa (job #2663106)
#include <fstream>
#include <vector>
using namespace std;
vector<vector<int>> graph;
vector<vector<int>> transposed_graph;
vector<bool> visited;
vector<int> node_order;
vector<vector<int>> components;
int componentCount = 0;
void dfs1(const int node)
{
if (visited[node])
return;
visited[node] = true;
for (auto neighbor : graph[node])
dfs1(neighbor);
node_order.push_back(node);
}
void dfs2(const int node)
{
if (visited[node])
return;
visited[node] = true;
components[componentCount].push_back(node);
for (auto neighbor : transposed_graph[node])
dfs2(neighbor);
}
int main()
{
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n, m;
fin >> n >> m;
graph = vector<vector<int>>(n, vector<int>());
transposed_graph = vector<vector<int>>(n, vector<int>());
visited = vector<bool>(n, false);
node_order = vector<int>();
node_order.reserve(n);
for (auto i = 0; i < m; i++)
{
int x, y;
fin >> x >> y;
x--;
y--;
graph[x].push_back(y);
transposed_graph[y].push_back(x);
}
fin.close();
for (auto i = 0; i < n; i++)
if (!visited[i])
dfs1(i);
for (auto&& i : visited)
i = false;
auto num_components = 0;
for (auto i = static_cast<int>(node_order.size()) - 1; i >= 0; i--)
{
const auto node = node_order[i];
components.emplace_back();
if (!visited[node])
dfs2(node);
componentCount++;
if (!components[componentCount - 1].empty())
num_components++;
}
fout << num_components << endl;
for (auto& component : components)
{
if (!component.empty())
{
for (auto node : component)
fout << node + 1 << " ";
fout << endl;
}
}
fout.close();
return 0;
}