Pagini recente » Cod sursa (job #2718133) | Istoria paginii runda/pre_oni_3_star/clasament | Cod sursa (job #129132) | Cod sursa (job #837542) | Cod sursa (job #2943760)
#include <bits/stdc++.h>
#define N 100007
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n,m,ct,temp;
vector<int>a[N],comp[N];
vector<int> low_link(N,0),disc(N,0);
vector<bool>instack(N,0);
stack<int>st;
void Citire()
{
fin >> n >> m;
for(int i=1;i<=m;i++)
{
int x,y;fin >> x >> y;
a[x].push_back(y);
}
fin.close();
}
void DFS(int x)
{
disc[x]=++temp;
low_link[x]=disc[x];
st.push(x);
instack[x]=1;
for(auto y:a[x])
{
if( disc[y] )
{
if( instack[y] )
low_link[x]=min(low_link[x],disc[y]);
}
else
{
DFS(y);
low_link[x]=min(low_link[x],low_link[y]);
}
}
if( low_link[x]==disc[x] )
{
ct++;
while( st.top()!=x )
{
comp[ct].push_back(st.top());
instack[st.top()]=0;
st.pop();
}
comp[ct].push_back(st.top());
st.pop();
}
}
void Tarjan()
{
for(int i=1;i<=n;i++)
if( !disc[i] )
DFS(i);
}
void Sortare_Afisare()
{
for(int i=1;i<=ct;i++)
sort( comp[i].begin(),comp[i].end() );
bool ok=1;
while(ok)
{
ok=!ok;
for(int i=1;i<=ct-1;i++)
if( comp[i][0]>comp[i+1][0] )
{
ok=1;
swap(comp[i],comp[i+1]);
}
}
fout << ct << "\n";
for(int i=1;i<=ct;i++,fout<<'\n')
for(auto y:comp[i])
fout << y << " ";
}
int main()
{
Citire();
Tarjan();
Sortare_Afisare();
return 0;
}