Pagini recente » Cod sursa (job #725191) | Cod sursa (job #1087827) | Cod sursa (job #1665773) | Cod sursa (job #2202184) | Cod sursa (job #2975978)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream f ("ctc.in");
ofstream g ("ctc.out");
const int SIZE = 100005;
int n, m, id, cnt;
int ids[SIZE], low[SIZE];
bool inStack[SIZE];
vector <int> adj[SIZE];
vector <int> ssc[SIZE];
stack <int> s;
void Read()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
f >> x >> y;
adj[x].push_back(y);
}
}
void Tarjan(int node)
{
s.push(node);
inStack[node] = true;
ids[node] = low[node] = ++id;
for (unsigned int i = 0; i < adj[node].size(); i++)
{
int neighbour = adj[node][i];
if (ids[neighbour] == 0)
{
Tarjan(neighbour);
}
if (inStack[neighbour] == true)
{
low[node] = min(low[node], low[neighbour]);
}
}
if (ids[node] == low[node])
{
cnt++;
int n = 0;
while (n != node)
{
n = s.top();
s.pop();
inStack[node] = false;
ssc[cnt].push_back(n);
}
}
}
void Print()
{
cout << cnt << "\n";
for (int i = 1; i <= cnt; i++)
{
for (unsigned int j = 0; j < ssc[i].size(); j++)
{
cout << ssc[i][j] << " ";
}
cout << "\n";
}
}
int main()
{
Read();
for (int i = 1; i <= n; i++)
{
if (ids[i] == 0)
{
Tarjan(i);
}
}
Print();
return 0;
}