Pagini recente » Cod sursa (job #2334437) | Cod sursa (job #677028) | Cod sursa (job #2588034) | Cod sursa (job #1578935) | Cod sursa (job #1833873)
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
const int NMAX = 100001;
int n;
vector < int > V[NMAX]; // graph
vector < int > Vt[NMAX];
vector < int > A[NMAX]; // elements of strongly connected components
stack < int > S;
bool seen[NMAX];
bool seen_t[NMAX];
int idx; // the number of strongly connected components
void read()
{
int m, x, y, i;
fin >> n >> m;
for (i = 1; i <= m; ++ i)
{
fin >> x >> y;
V[x].push_back(y);
Vt[y].push_back(x);
}
}
void dfs(int node)
{
vector < int > :: iterator it;
seen[node] = true;
for (it = V[node].begin(); it != V[node].end(); ++ it)
if (!seen[*it])
dfs(*it);
S.push(node);
}
void end_time()
{
int i;
for (i = 1; i <= n; ++ i)
if (!seen[i])
dfs(i);
}
void dfs_t(int node)
{
vector < int > :: iterator it;
seen_t[node] = true;
for (it = Vt[node].begin(); it != Vt[node].end(); ++ it)
if (!seen_t[*it])
dfs_t(*it);
A[idx].push_back(node);
}
void tarjan()
{
while (!S.empty())
if (!seen_t[S.top()])
{
++ idx;
dfs_t(S.top());
}
else
S.pop();
}
void print()
{
int i;
vector < int > :: iterator it;
fout << idx << "\n";
for (i = 1; i <= idx; ++ i)
{
for (it = A[i].begin(); it != A[i].end(); ++ it)
fout << *it << " ";
fout << "\n";
}
}
int main()
{
read();
fin.close();
end_time();
tarjan();
print();
fout.close();
return 0;
}