Pagini recente » Cod sursa (job #851607) | Cod sursa (job #2486710) | Cod sursa (job #421201) | Cod sursa (job #2712584) | Cod sursa (job #3225011)
#include <fstream>
#include <vector>
#include <algorithm>
#include <bitset>
using namespace std;
const int N = 1e5;
vector <int> succ[N+1];
vector <int> pred[N+1];
vector <vector <int>> ctc;
vector <int> sort_top;
bitset <N+1> viz;
void dfs(int x)
{
viz[x] = 1;
for (auto y: succ[x])
{
if (!viz[y])
{
dfs(y);
}
}
sort_top.push_back(x);
}
void dfs_t(int x, vector <int> &c)
{
viz[x] = 1;
c.push_back(x);
for (auto y: pred[x])
{
if (!viz[y])
{
dfs_t(y, c);
}
}
}
int main()
{
ifstream in("ctc.in");
ofstream out("ctc.out");
int n, m;
in >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y;
in >> x >> y;
succ[x].push_back(y);
pred[y].push_back(x);
}
///etapa 1: construim cu apeluri dfs vectorul sort_top
for (int x = 1; x <= n; x++)
{
if (!viz[x])
{
dfs(x);
}
}
///etapa 2: parcurgem in ordine inversa sort_top si apelam dfs_t
viz.reset();
reverse(sort_top.begin(), sort_top.end());
for (auto x: sort_top)
{
if (!viz[x])
{
vector <int> aux;
dfs_t(x, aux);
ctc.push_back(aux);
}
}
out << ctc.size() << "\n";
for (auto c: ctc)
{
for (auto x: c)
{
out << x << " ";
}
out << "\n";
}
in.close();
out.close();
return 0;
}