Pagini recente » Istoria paginii winter-challenge-2008 | Scrie articole | Documentatie | Documentatie | Cod sursa (job #3294953)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
vector <vector <int>> su, pr;
vector <vector <int>> ctc;
vector <bool> viz;
vector <int> ps_sort;
void dfs_su(int x)
{
viz[x] = true;
for (auto y: su[x])
{
if (!viz[y])
{
dfs_su(y);
}
}
ps_sort.push_back(x);
}
void dfs_pr(int x, vector <int> &c)
{
viz[x] = true;
c.push_back(x);
for (auto y: pr[x])
{
if (!viz[y])
{
dfs_pr(y, c);
}
}
}
int main()
{
ifstream in("ctc.in");
ofstream out("ctc.out");
int n, m;
in >> n >> m;
su.resize(n + 1);
pr.resize(n + 1);
for (int i = 0; i < m; i++)
{
int x, y;
in >> x >> y;
su[x].push_back(y);
pr[y].push_back(x);
}
viz.resize(n + 1, false);
for (int i = 1; i <= n; i++)
{
if (!viz[i])
{
dfs_su(i);
}
}
fill(viz.begin(), viz.end(), false);
reverse(ps_sort.begin(), ps_sort.end());
for (auto x: ps_sort)
{
if (!viz[x])
{
vector <int> comp;
dfs_pr(x, comp);
ctc.push_back(comp);
}
}
out << ctc.size() << "\n";
for (auto c: ctc)
{
for (auto x: c)
{
out << x << " ";
}
out << "\n";
}
in.close();
out.close();
return 0;
}