Pagini recente » Cod sursa (job #2110223) | Cod sursa (job #2842520) | Cod sursa (job #263) | Cod sursa (job #2881552) | Cod sursa (job #2792044)
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
int n, m;
vector<vector<int>> G, Gt;
vector<bool> visited;
stack<int> stk;
vector<int> cc;
vector<vector<int>> ctc;
void Read();
void Dfs1(int x);
void Dfs2(int x);
void Write();
int main()
{
Read();
for (int x = 1; x <= n; x++)
if (!visited[x])
Dfs1(x);
visited = vector<bool>(n + 1);
int x;
while (!stk.empty())
{
x = stk.top();
stk.pop();
if (!visited[x])
{
cc = vector<int>();
Dfs2(x);
ctc.emplace_back(cc);
}
}
Write();
}
void Dfs2(int x)
{
visited[x] = true;
cc.emplace_back(x);
for (const int& y : G[x])
if (!visited[y])
Dfs2(y);
}
void Dfs1(int x)
{
visited[x] = true;
for (const int& y : Gt[x])
if (!visited[y])
Dfs1(y);
stk.emplace(x);
}
void Write()
{
ofstream fout("ctc.out");
fout << ctc.size() << '\n';
for (const auto& c : ctc)
{
for (const int& x : c)
fout << x << ' ';
fout << '\n';
}
}
void Read()
{
ifstream fin("ctc.in");
fin >> n >> m;
G = Gt = vector<vector<int>>(n + 1);
visited = vector<bool>(n + 1);
int x, y;
while (m--)
{
fin >> x >> y;
G[x].emplace_back(y);
Gt[y].emplace_back(x);
}
}