Pagini recente » Cod sursa (job #632207) | Cod sursa (job #458081) | Diferente pentru problema/interact intre reviziile 59 si 60 | Cod sursa (job #147102) | Cod sursa (job #3344409)
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100005;
vector<int> scc, graph[MAX], rgraph[MAX];
vector<vector<int>> ans;
int visited[MAX], topSort[MAX], k;
void dfs(int node)
{
visited[node] = 1;
for (int next : graph[node])
if (!visited[next])
dfs(next);
topSort[++k] = node;
}
void kosaraju(int node)
{
visited[node] = 1;
scc.push_back(node);
for (int next : rgraph[node])
if (!visited[next])
kosaraju(next);
}
int main()
{
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n, m;
fin >> n >> m;
for (int i = 1; i <= m; ++i)
{
int x, y;
fin >> x >> y;
graph[x].push_back(y);
rgraph[y].push_back(x);
}
for (int i = 1; i <= n; ++i)
if (!visited[i])
dfs(i);
for (int i = 1; i <= n; ++i)
visited[i] = 0;
for (int i = k; i >= 1; --i)
{
int next = topSort[i];
if (!visited[next])
{
scc.clear();
kosaraju(next);
ans.push_back(scc);
}
}
fout << ans.size() << "\n";
for (vector<int> cmp : ans)
{
for (int node : cmp)
fout << node << " ";
fout << "\n";
}
return 0;
}