Pagini recente » Cod sursa (job #3289613) | Cod sursa (job #2462497) | Cod sursa (job #1116862) | Cod sursa (job #3279036) | Cod sursa (job #3211086)
#include <fstream>
#include <algorithm>
#include <vector>
#define MAX 50000
using namespace std;
ifstream cin ("ctc.in");
ofstream cout ("ctc.out");
int vis[MAX + 10], st[MAX + 10], cnt, cntComp;
vector <int> graph[MAX + 10], graphInv[MAX + 10], comp[MAX + 10];
void dfs(int node)
{
vis[node] = 1;
for (const auto &next : graph[node])
if (vis[next] == 0)
dfs(next);
cnt++;
st[cnt] = node;
}
void dfsCTC(int node)
{
vis[node] = 1;
for (const auto &next : graphInv[node])
if (vis[next] == 0)
dfsCTC(next);
comp[cntComp].push_back(node);
}
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
cin >> x >> y;
graph[x].push_back(y);
graphInv[y].push_back(x);
}
for (int i = 1; i <= n; i++)
if (vis[i] == 0)
dfs(i);
reverse(st + 1, st + n + 1);
for (int i = 1; i <= n; i++)
vis[i] = 0;
for (int i = 1; i <= n; i++)
if (vis[st[i]] == 0)
{
cntComp++;
dfsCTC(st[i]);
}
cout << cntComp << '\n';
for (int i = 1; i <= cntComp; i++)
{
for (const auto &it : comp[i])
cout << it << ' ';
cout << '\n';
}
return 0;
}