Pagini recente » Cod sursa (job #1688716) | Cod sursa (job #2169209) | Cod sursa (job #2067257) | Cod sursa (job #922827) | Cod sursa (job #717519)
Cod sursa(job #717519)
#include <cstdio>
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <cstring>
using namespace std;
#define maxN 100005
#define PB push_back
int N , M , cost[maxN] , comp , step;
bool in_S[maxN];
vector <int> lista[maxN] , sol[maxN];
stack <int> P , S;
void get_component (int node)
{
++comp;
while (!S.empty () && S.top () != node)
{
sol[comp].PB (S.top ());
in_S[S.top ()] = false;
S.pop ();
}
if (!S.empty ())
{
sol[comp].PB (S.top ());
in_S[S.top ()] = false;
S.pop ();
}
}
void pop_useless (int reference)
{
while (!P.empty () && cost[P.top ()] > reference)
P.pop ();
}
void Gabow (int X)
{
cost[X] = step;
++step;
S.push (X);
P.push (X);
in_S[X] = true;
for (unsigned int i = 0 ; i < lista[X].size () ; ++i)
{
int nodcur = lista[X][i];
if (cost[nodcur] == -1)
Gabow (nodcur);
else
{
if (in_S[nodcur])
pop_useless (cost[nodcur]);
}
}
if (!P.empty () && X == P.top ())
{
get_component (X);
P.pop ();
}
}
int main ()
{
freopen ("ctc.in" , "r" , stdin);
freopen ("ctc.out" , "w" , stdout);
scanf ("%d %d" , &N , &M);
int a , b;
for (int i = 1 ; i <= M ; ++i)
{
scanf ("%d %d" , &a , &b);
lista[a].PB (b);
}
memset (cost , -1 , sizeof (cost));
for (int i = 1 ; i <= N ; ++i)
if (cost[i] == -1)
Gabow (i);
/*for (int i = 1 ; i <= N ; ++i)
cout << cost[i] << " ";*/
printf ("%d\n" , comp);
for (int t = 1 ; t <= comp ; ++t)
{
for (unsigned int i = 0 ; i < sol[t].size () ; ++i)
printf ("%d " , sol[t][i]);
printf ("\n");
}
return 0;
}