Pagini recente » Cod sursa (job #1912009) | Cod sursa (job #2123221) | Cod sursa (job #1328780) | Cod sursa (job #904776) | Cod sursa (job #1877832)
/* punctaj :
Algoritmul lui Tarjan -> se comporta foarte bine in practica
*/
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
const int MAXN = 100005;
using VI = vector<int>;
vector<VI> G;
VI ind, low;
stack<int> st;
int N, M;
int index{1};
bool is[MAXN];
vector<vector<int>> ctc;
void ReadGraph();
void Tarjan();
void Write();
void DFS( int x );
int main()
{
ReadGraph();
Tarjan();
Write();
fin.close();
fout.close();
return 0;
}
void ReadGraph()
{
int x, y;
fin >> N >> M;
G = vector<VI>(N + 1);
low = ind = VI(N + 1);
while ( M-- )
{
fin >> x >> y;
G[x].push_back(y);
}
}
void Tarjan()
{
for ( int i = 1; i <= N; ++i )
if ( !ind[i] )
DFS(i);
}
void Write()
{
fout << ctc.size() << '\n';
for ( const auto& x : ctc )
{
for ( const int& y : x )
fout << y << ' ';
fout << '\n';
}
}
void DFS( int x )
{
ind[x] = low[x] = index;
++index;
st.push(x); is[x] = 1;
for ( const int& y : G[x] )
{
if ( !ind[y] )
{
DFS(y);
low[x] = min( low[x], low[y] );
}
else
if ( is[y] )
low[x] = min( low[x], low[y] );
}
if ( ind[x] == low[x] )
{
VI c;
int n;
do
{
c.push_back( n = st.top() );
st.pop(); is[n] = 0;
}while ( n != x );
ctc.push_back(c);
}
}