Pagini recente » Cod sursa (job #540392) | Cod sursa (job #2490404) | Cod sursa (job #894383) | Cod sursa (job #998016) | Cod sursa (job #3260035)
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <stack>
using namespace std;
const int nmax = 100005;
vector<int> G[nmax];
vector<int> GI[nmax];
ifstream f("ctc.in");
ofstream g("ctc.out");
int n, m;
int viz[nmax];
int adaugat[nmax];
stack<int>lista;
vector<int> componente[nmax];
int totale;
void read()
{
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);
}
}
void dfs(int nod)
{
viz[nod] = 1;
for(auto it : G[nod])
{
if (!viz[it])
{
dfs(it);
}
}
lista.push(nod);
}
void assign(int nod, int root)
{
adaugat[nod] = 1;
componente[root].push_back(nod);
for (auto it : GI[nod])
{
if (!adaugat[it])
{
assign(it, root);
}
}
}
int main()
{
read();
for (int i = 1; i <= n; i++)
{
if (!viz[i])
{
dfs(i);
}
}
while (!lista.empty())
{
if (!adaugat[lista.top()])
{
assign(lista.top(), totale);
totale++;
}
lista.pop();
}
g << totale << '\n';
for (int i = 0; i <= n-1; i++)
{
if (!componente[i].empty())
{
for (auto it : componente[i])
{
g << it << " ";
}
g << '\n';
}
}
return 0;
}