Pagini recente » Cod sursa (job #1726522) | Cod sursa (job #2381758) | Cod sursa (job #2629280) | Cod sursa (job #318032) | Cod sursa (job #2663104)
#include <fstream>
#include <vector>
using namespace std;
vector<vector<int>> graph;
vector<vector<int>> transposed_graph;
vector<bool> visited;
vector<int> node_order;
vector<int> current_node_set;
int current_component_index = 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;
current_node_set[current_component_index++] = 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);
current_node_set = vector<int>(n, 0);
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;
for (auto i = static_cast<int>(node_order.size()) - 1; i >= 0; i--)
{
const auto node = node_order[i];
current_component_index = 0;
if (!visited[node])
dfs2(node);
for (auto j = 0; j < current_component_index; j++)
fout << current_node_set[j] + 1 << " ";
if (current_component_index)
fout << endl;
}
fout.close();
return 0;
}