Pagini recente » Cod sursa (job #2917474) | Cod sursa (job #1351902) | Cod sursa (job #458473) | Cod sursa (job #1291102) | Cod sursa (job #2790322)
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <string.h>
#define N 100001
using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");
vector<int> graph[N];
vector<int> rev_graph[N];
int n;
stack<int> top;
bool vis[N];
int nrcomp;
vector<int> ans[N];
void dfs1(int x)
{
for(auto y: rev_graph[x])
{
if(!vis[y])
{
vis[y]=1;
dfs1[y];
}
}
top.push(x);
}
void dfs2(int x, int nr)
{
for(auto y: graph[x])
{
if(!vis[y])
{
vis[y]=1;
dfs2(y,nr);
}
}
ans[nr].push_back(x);
}
int main()
{
//memset(scc,-1,sizeof(scc));
int m;
in >> n >> m;
for(int i=0;i<m;i++)
{
int x,y;
in >> x >> y;
graph[x].push_back(y);
rev_graph[y].push_back(x);
}
for(int i=1;i<=n;i++)
{
if(!vis[i])
{
vis[i]=1;
dfs1(i);
}
}
memset(vis, 0, sizeof(vis));
while(!top.empty())
{
int x=top.top();
top.pop();
if(!vis[x])
{
nrcomp++;
vis[x]=1;
dfs2(x,nrcomp);
}
}
out << nrcomp << "\n";
for(int i=1;i<=nrcomp;i++)
{
for(auto y:ans[i])
{
out << y << " ";
}
out << "\n";
}
return 0;
}