Pagini recente » Cod sursa (job #366506) | Cod sursa (job #3195428) | Cod sursa (job #2839168) | Cod sursa (job #2751763) | Cod sursa (job #1282134)
#include <cstdio>
#include <vector>
#include <stack>
using namespace std;
vector<int> g[100001];
stack<int> st;
struct V
{
int index;
int lowlink;
};
V v[100001];
int sol[100001];
int index = 0;
bool in_stack[100001];
bool new_line[100001];
int nr_sol = 0;
void scc(int x)
{
in_stack[x] = 1;
st.push(x);
v[x].index = ++index;
v[x].lowlink = index;
for (int i = 0; i < g[x].size(); ++i)
if (v[g[x][i]].index == 0)
{
scc(g[x][i]);
v[x].lowlink = min(v[x].lowlink, v[g[x][i]].lowlink);
}
else
if (in_stack[g[x][i]])
{
v[x].lowlink = min(v[x].lowlink, v[g[x][i]].index);
}
if (v[x].index == v[x].lowlink)
{
++nr_sol;
new_line[sol[0]+1] = 1;
if (x != st.top())
{
sol[++sol[0]] = st.top();
in_stack[st.top()] = 0;
st.pop();
while (x != st.top())
{
sol[++sol[0]] = st.top();
in_stack[st.top()] = 0;
st.pop();
}
}
sol[++sol[0]] = st.top();
in_stack[st.top()] = 0;
st.pop();
}
}
int main()
{
FILE *in = fopen("ctc.in", "r");
FILE *out = fopen("ctc.out", "w");
int n, m;
fscanf(in, "%d%d", &n, &m);
for (int x, y; m > 0; --m)
{
fscanf(in, "%d%d", &x, &y);
g[x].push_back(y);
}
for (int i = 1; i <= n; ++i)
if (v[i].index == 0)
scc(i);
fprintf(out, "%d", nr_sol);
for (int i = 1; i <= n; ++i)
if (new_line[i])
fprintf(out, "\n%d", sol[i]);
else
fprintf(out, " %d", sol[i]);
fprintf(out, "\n");
fclose(in);
fclose(out);
return 0;
}