Pagini recente » Cod sursa (job #1077215) | Cod sursa (job #2156556) | Cod sursa (job #2812689) | Cod sursa (job #3126796) | Cod sursa (job #3183765)
#include <iostream>
#include <fstream>
#include <queue>
#include <stack>
#include <cmath>
#include <vector>
using namespace std;
ifstream f("ctc.in");
ofstream g("ctc.out");
const int nmax = 100005;
int n, m;
vector<int>G[nmax], GI[nmax];
bool viz[nmax];
stack<int>lista;
vector<vector<int>>componente;
bool adaugat[nmax];
void dfs(int nod)
{
viz[nod] = 1;
for (auto nbr : G[nod])
{
if (!viz[nbr])
{
dfs(nbr);
}
}
lista.push(nod);
}
void assign(int nod, int tatic)
{
adaugat[nod] = 1;
componente[tatic].push_back(nod);
for (auto nbr : GI[nod])
{
if (!adaugat[nbr])
{
assign(nbr, tatic);
}
}
}
int main()
{
f >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
f >> x >> y;
G[x].push_back(y);
GI[y].push_back(x);
}
for (int i = 1; i <= n; i++)
{
if (!viz[i])
{
dfs(i);
}
}
componente.resize(n+1);
int total = 0;
while (!lista.empty())
{
if (!adaugat[lista.top()])
{
assign(lista.top(), lista.top());
total++;
}
lista.pop();
}
g << total << '\n';
for (int i = 1; i <= n; i++)
{
if (!componente[i].empty())
{
for (auto it : componente[i])
{
g << it << ' ';
}
g << '\n';
}
}
}