Pagini recente » Cod sursa (job #1540192) | Cod sursa (job #1530263) | Cod sursa (job #1855384) | Cod sursa (job #547047) | Cod sursa (job #2790328)
#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)
{
for(auto y: graph[x])
{
if(!vis[y])
{
vis[y]=1;
dfs2(y);
}
}
ans[nrcomp].push_back(x);
}
int main()
{
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);
}
}
out << nrcomp << "\n";
for(int i=1;i<=nrcomp;i++)
{
for(auto y:ans[i])
{
out << y << " ";
}
out << "\n";
}
return 0;
}