Pagini recente » Cod sursa (job #1264225) | Cod sursa (job #1299327) | Cod sursa (job #3158973) | Cod sursa (job #2017915) | Cod sursa (job #3301642)
#include <bits/stdc++.h>
std::ifstream fin("ctc.in");
std::ofstream fout("ctc.out");
//#define fin std::cin
//#define fout std::cout
const int nmax = 1e5 + 5;
int n, m;
std::vector<int> graph[nmax];
int curr_idx;
int lowlink[nmax], index[nmax];
bool on_stack[nmax];
std::stack<int> st;
int ctc_count;
std::vector<int> ctc_comp[nmax];
void buildCTC(int node)
{
index[node] = ++curr_idx;
lowlink[node] = index[node];
on_stack[node] = true;
st.push(node);
for(auto adj : graph[node])
{
if(!index[adj])
{
buildCTC(adj);
lowlink[node] = std::min(lowlink[node], lowlink[adj]);
}
else if(on_stack[adj])
lowlink[node] = std::min(lowlink[node], lowlink[adj]);
}
if(lowlink[node] == index[node])
{
ctc_count++;
int curr_node;
do
{
curr_node = st.top();
st.pop();
on_stack[curr_node] = false;
ctc_comp[ctc_count].push_back(curr_node);
}
while(curr_node != node);
}
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; ++i)
{
int x, y;
fin >> x >> y;
graph[x].push_back(y);
}
for(int i = 1; i <= n; ++i)
if(!index[i])
buildCTC(i);
fout << ctc_count << "\n";
for(int i = 1; i <= ctc_count; ++i, fout << "\n")
for(auto node : ctc_comp[i])
fout << node << " ";
return 0;
}