Pagini recente » Borderou de evaluare (job #3295177) | Cod sursa (job #1180604) | Cod sursa (job #2003744) | Cod sursa (job #3346162) | Cod sursa (job #3335071)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("ctc.in");
ofstream fout ("ctc.out");
int n, m;
vector <int> g[100001], invg[100001], comp[100001];
bool viz[100001];
void dfs(int node, vector <int> &sorted)
{
viz[node] = true;
for (auto vecin : g[node])
{
if (!viz[vecin])
{
dfs(vecin, sorted);
}
}
sorted.push_back(node);
}
void det_comp(int node, vector <int> &comp)
{
for (auto vecin : invg[node])
if (viz[vecin])
{
viz[vecin] = false;
comp.push_back(vecin);
det_comp(vecin, comp);
}
}
void topo_sort(vector <int> &sorted)
{
for (int node = 1; node <= n; node++)
{
if (!viz[node])
dfs(node, sorted);
}
reverse(sorted.begin(), sorted.end());
}
int main()
{
fin >> n >> m;
for (int i = 1; i <= m ; i++)
{
int x, y;
fin >> x >> y;
g[x].push_back(y);
invg[y].push_back(x);
}
vector <int> sortat;
topo_sort(sortat);
int nrcomp = 0;
for (auto node : sortat)
if (viz[node])
det_comp(node, comp[++nrcomp]);
fout << nrcomp << '\n';
for (int i = 1; i <= nrcomp; i++)
{
for (auto node : comp[i])
fout << node << ' ';
fout << '\n';
}
return 0;
}