Pagini recente » Cod sursa (job #169595) | Cod sursa (job #1302010) | Cod sursa (job #2673850) | Cod sursa (job #362813) | Cod sursa (job #2090769)
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
using VI = vector<int>;
using VVI = vector<VI>;
using VB = vector<bool>;
VVI G, Gt, ctc;
stack<int> stk;
VI c;
VB v;
int n, m;
void ReadGraph();
void Kosaraju();
void Df(int x);
void DfT(int x);
void Write();
int main()
{
ReadGraph();
Kosaraju();
Write();
}
void Df(int x)
{
v[x] = true;
for (const int& y : G[x])
if (!v[y])
Df(y);
stk.push(x);
}
void DfT(int x)
{
v[x] = true;
c.push_back(x);
for (const int& y : Gt[x])
if (!v[y])
DfT(y);
}
void Kosaraju()
{
for (int x = 1; x <= n; x++)
if (!v[x])
Df(x);
int x;
v = VB(n + 1);
while (!stk.empty())
{
x = stk.top();
stk.pop();
if (v[x])
continue;
c.clear();
DfT(x);
ctc.push_back(c);
}
}
void Write()
{
ofstream fout("ctc.out");
fout << ctc.size() << '\n';
for (VI& c : ctc)
{
for (const int& x : c)
fout << x << ' ';
fout << '\n';
}
fout.close();
}
void ReadGraph()
{
ifstream fin("ctc.in");
fin >> n >> m;
G = Gt = VVI(n + 1);
v = VB(n + 1);
int x, y;
while (m--)
{
fin >> x >> y;
G[x].push_back(y);
Gt[y].push_back(x);
}
fin.close();
}