Pagini recente » Cod sursa (job #390343) | Cod sursa (job #1212816) | Cod sursa (job #667100) | Cod sursa (job #1178715) | Cod sursa (job #2442698)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define NMax 100005
using namespace std;
ifstream fin("graf.in");
ofstream fout("graf.out");
stack <int> S;
vector<int> G[NMax],GT[NMax],CTC[NMax];
int N, M, NrCTC;
int beenThere[NMax];
void Read()
{
fin >> N >> M;
for(int i = 1; i <= M; i++)
{
int x,y;
fin >> x >> y;
G[x].push_back(y);
GT[y].push_back(x);
}
}
void DFSP(int Nod)
{
beenThere[Nod] = 1;
for(int i=0; i<G[Nod].size();i++) {
int Vecin = G[Nod][i];
if(!beenThere[Vecin])
DFSP(Vecin);
}
S.push(Nod);
}
void DFSM(int Nod)
{
beenThere[Nod] = 2;
CTC[NrCTC].push_back(Nod);
for(int i=0; i<GT[Nod].size(); i++)
{
int Vecin = GT[Nod][i];
if(beenThere[Vecin]==1)
DFSM(Vecin);
}
}
void Solve()
{
for(int i=1;i<=N;i++)
if(!beenThere[i])
DFSP(i);
while(!S.empty())
{
int Nod = S.top();
if (beenThere[Nod] == 1)
{
NrCTC++;
DFSM(Nod);
}
S.pop();
}
}
void Print()
{
fout << NrCTC <<"\n";
for(int i = 1; i <= NrCTC; i++)
{
for(int j = 0; j < CTC[i].size(); j++)
fout << CTC[i][j] <<" ";
fout<<"\n";
}
}
int main()
{
Read();
Solve();
Print();
return 0;
}