Pagini recente » Cod sursa (job #976306) | Cod sursa (job #2548099) | Cod sursa (job #1112642) | Cod sursa (job #1681987) | Cod sursa (job #1541349)
#include <cstdio>
#include <bitset>
#include <stack>
#include <vector>
#define NMAX 100001
#define INF (1 << 30)
using namespace std;
bitset<NMAX> onStack;
vector<int> children[NMAX];
vector<stack<int> > solution;
stack<int> st;
int n, m, count, index[NMAX], minim[NMAX];
void readInput() {
freopen("ctc.in", "r", stdin);
freopen("ctc.out", "w", stdout);
int a, b;
scanf("%d %d", &n, &m);
for (int i = 0; i < m; i++) {
scanf("%d %d", &a, &b);
children[a].push_back(b);
}
for (int i = 1; i <= n; i++) {
index[i] = INF;
}
}
void push(int idx) {
onStack[idx] = 1;
index[idx] = minim[idx] = ++count;
st.push(idx);
// printf("Push %d with %d\n", idx, minim[idx]);
}
void pop(int idx) {
if (minim[idx] == index[idx]) {
int top;
solution.push_back(stack<int>());
do {
top = st.top();
onStack[top] = 0;
st.pop();
solution.back().push(top);
// printf("Pop %d with %d\n", top, minim[top]);
} while (top != idx);
}
}
void visit(int idx) {
push(idx);
for (size_t i = 0; i < children[idx].size(); i++) {
int child = children[idx][i];
if (index[child] == INF) {
visit(child);
minim[idx] = min(minim[idx], minim[child]);
} else if (onStack[child]) {
minim[idx] = min(minim[idx], index[child]);
}
}
pop(idx);
}
int main() {
readInput();
for (int i = 1; i <= n; i++) {
if (index[i] == INF) {
visit(i);
}
}
printf("%u\n", solution.size());
for (size_t i = 0; i < solution.size(); i++) {
while (!solution[i].empty()) {
printf("%d ", solution[i].top());
solution[i].pop();
}
printf("\n");
}
return 0;
}