Pagini recente » Cod sursa (job #2594292) | Cod sursa (job #479682) | Cod sursa (job #479668) | Cod sursa (job #2594172) | Cod sursa (job #3215605)
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream cin("ctc.in");
ofstream cout("ctc.out");
int n,m;
int k;
vector<vector<int>> A;
vector<int> low_link,indicativ;
vector<bool> fr,frs;
stack<int> S;
int x,y;
vector<vector<int>> ans;
void dfs(int nod)
{
indicativ[nod]=k++;
low_link[nod]=indicativ[nod];
S.push(nod);
frs[nod]=1;
for(int i=0;i<A[nod].size();i++)
{
int vecin=A[nod][i];
if(!fr[vecin])
{
fr[vecin]=1;
dfs(vecin);
}
if(frs[vecin])
low_link[nod]=min(low_link[nod],low_link[vecin]);
}
if(low_link[nod]==indicativ[nod])
{
ans.resize(ans.size()+1);
while(S.top()!=nod)
{
ans[ans.size()-1].push_back(S.top());
frs[S.top()]=0;
S.pop();
}
ans[ans.size()-1].push_back(S.top());
S.pop();
frs[nod]=0;
}
}
int main()
{
cin>>n>>m;
A.resize(n+1);
low_link.resize(n+1);
indicativ.resize(n+1);
fr.resize(n+1);
frs.resize(n+1);
for(int i=0;i<m;i++)
{
cin>>x>>y;
A[x].push_back(y);
}
for(int i=1;i<=n;i++)
if(!fr[i])
{
fr[i]=1;
dfs(i);
}
cout<<ans.size()-1<<'\n';
for(int i=0;i<ans.size();i++)
{
for(int j=0;j<ans[i].size();j++)
cout<<ans[i][j]<<" ";
cout<<'\n';
}
return 0;
}