Pagini recente » Cod sursa (job #2664712) | Cod sursa (job #2582860) | Cod sursa (job #238660) | Cod sursa (job #1464392) | Cod sursa (job #2088635)
// Det Comp Tare Conexe
// Alg. lui Tarjan
// O(m)
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
enum {
White, Gray, Black
};
using VI = vector<int>;
using VVI = vector<VI>;
using VB = vector<bool>;
int n, m;
VVI G; // graful
VI niv; // niv[x] = timpul de descoperire a nodului x (index)
VI L;
VI color;
VB inStack;
int idx; // timpul curent
VVI cc; // retine comp tare conexe
VI c; // comp tare conexa curenta
stack<int> stk;
void ReadGraph();
void Tarjan(int x);
void StronglyConnectedComp();
void Write();
int main()
{
ReadGraph();
StronglyConnectedComp();
Write();
fin.close();
fout.close();
}
void StronglyConnectedComp()
{
for (int x = 1; x <= n; ++x) // O(m)
if (niv[x] == 0)
Tarjan(x);
}
void Tarjan(int x)
{
niv[x] = L[x] = ++idx;
stk.push(x); inStack[x] = true;
color[x] = Gray;
for (const int& y : G[x])
if (color[y] == White) // tree edge
{
Tarjan(y);
L[x] = min(L[x], L[y]);
}
else
if (color[y] == Gray) // daca e in stiva, atunci e stramos => back edge
L[x] = min(L[x], niv[y]);
if (L[x] == niv[x]) // x e reprezentantul unei C.T.C
{
c.clear();
while (!stk.empty())
{
int z = stk.top();
stk.pop();
inStack[z] = false;
c.push_back(z);
if (z == x)
break;
}
cc.push_back(c);
}
color[x] = Black;
}
void ReadGraph()
{
fin >> n >> m;
G = VVI(n + 1);
L = niv = color = VI(n + 1);
inStack = VB(n + 1);
int x, y;
while (m--)
{
fin >> x >> y;
G[x].push_back(y);
}
}
void Write()
{
fout << cc.size() << '\n';
for (auto& c : cc)
{
for (auto& x : c)
fout << x << ' ';
fout << '\n';
}
}