Pagini recente » Cod sursa (job #2402194) | Cod sursa (job #397903) | Cod sursa (job #283275) | Cod sursa (job #927895) | Cod sursa (job #921717)
Cod sursa(job #921717)
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
const int MAX_N = 100002;
int N, M, NrSCC, x, y, ind;
int index[MAX_N], lowlink[MAX_N], in_st[MAX_N];
vector < int > v[MAX_N], SCC[MAX_N];
stack < int > st;
inline void strong_connect(int x)
{
++ind;
index[x] = lowlink[x] = ind;
st.push(x), in_st[x] = 1;
for(int i = 0; i < v[x].size(); ++i)
{
int y = v[x][i];
if(!index[y])
{
strong_connect(y);
lowlink[x] = min(lowlink[x], lowlink[y]);
}
else if(in_st[y])
lowlink[x] = min(lowlink[x], index[y]);
}
if(index[x] == lowlink[x])
{
++NrSCC;
do
{
y = st.top(), st.pop();
SCC[NrSCC].push_back(y);
in_st[y] = 0;
}while(y != x);
}
}
int main()
{
ifstream f("ctc.in");
ofstream g("ctc.out");
f >> N >> M;
for(int i = 1; i <= M; ++i)
{
f >> x >> y;
v[x].push_back(y);
}
for(int i = 1; i <= N; ++i)
if(!index[i])
strong_connect(i);
g << NrSCC << '\n';
for(int i = 1; i <= NrSCC; ++i)
{
for(int j = 0; j < SCC[i].size(); ++j)
g << SCC[i][j] << " ";
g << '\n';
}
f.close();
g.close();
return 0;
}