Pagini recente » Cod sursa (job #2546399) | Cod sursa (job #3142850) | Cod sursa (job #1564293) | Cod sursa (job #1901283) | Cod sursa (job #3232638)
#include <iostream>
#include <vector>
#include <bitset>
#include <fstream>
#include <stack>
using namespace std;
const int N = 1e5 + 1;
vector <int> L[N], T[N];
int n, m;
bitset <N> viz;
stack <int> st;
vector < vector <int> > ctc;
void Read()
{
ifstream fin("ctc.in");
fin >> n >> m;
while (m--)
{
int x, y;
fin >> x >> y;
L[x].push_back(y);
T[y].push_back(x);
}
}
void DFS1(int nod)
{
viz[nod] = 1;
for (auto next : L[nod])
if (!viz[next])
DFS1(next);
st.push(nod);
}
void DFS2(int nod)
{
viz[nod] = 1;
ctc.back().push_back(nod);
for (auto next : T[nod])
if (!viz[next])
DFS2(next);
}
void Kosaraju()
{
for (int i = 1; i <= n; i++)
if (!viz[i])
DFS1(i);
viz.reset();
while (!st.empty()) {
int curr = st.top();
st.pop();
if (!viz[curr]) {
ctc.push_back({});
DFS2(curr);
}
}
ofstream fout("ctc.in");
fout << ctc.size() << '\n';
for (auto& comp : ctc)
{
for (auto& it : comp)
fout << it << " ";
fout << '\n';
}
}
int main()
{
Read();
Kosaraju();
return 0;
}