Pagini recente » Borderou de evaluare (job #1569196) | Cod sursa (job #1980891) | Cod sursa (job #1154765) | Cod sursa (job #741619) | Cod sursa (job #2376248)
#include <fstream>
#include <vector>
#include <stack>
#define Nmax 100001
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int N, M, k, nrCTC;
int Viz[100001];
stack <int> St;
vector <int> G[Nmax], GT[Nmax], Raspuns[Nmax];
void Read()
{
int x, y;
fin >> N >> M;
for (int i=1; i<=M; i++)
{
fin >> x >> y;
G[x].push_back(y);
GT[y].push_back(x);
}
}
void DFS(int Nod)
{
Viz[Nod] = 1;
for (unsigned int i=0; i<G[Nod].size(); i++)
{
int Vecin = G[Nod][i];
if (Viz[Vecin] == 0)
{
DFS(Vecin);
}
}
St.push(Nod);
}
void DFS_2(int Nod)
{
Viz[Nod] = 2;
Raspuns[nrCTC].push_back(Nod);
for (unsigned int i=0; i<GT[Nod].size(); i++)
{
int Vecin = GT[Nod][i];
if (Viz[Vecin] == 1)
{
DFS_2(Vecin);
}
}
}
void Solve()
{
while (!St.empty())
{
int Nod = St.top();
if (Viz[Nod] == 1)
{
nrCTC++;
DFS_2(Nod);
}
St.pop();
}
}
void Write()
{
fout << nrCTC << '\n';
for (int i=1; i<=nrCTC; i++)
{
for(unsigned int j = 0; j < Raspuns[i].size(); j++)
fout << Raspuns[i][j] << " ";
fout << '\n';
}
}
int main()
{
Read();
for (int i=1; i<=N; i++)
if (Viz[i] == 0)
DFS(i);
Solve();
Write();
return 0;
}