Pagini recente » Cod sursa (job #2936417) | Cod sursa (job #843007) | Cod sursa (job #539109) | Cod sursa (job #2322126) | Cod sursa (job #1377094)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream f ("ctc.in");
ofstream g ("ctc.out");
const int NMAX = 100000 + 1;
int n, m, index_crt, nrcomp;
int lowlink[NMAX], index[NMAX];
bool in_stack[NMAX];
int comp[NMAX];
stack <int> st;
vector <int> graf[NMAX];
void citeste() {
int a, b;
f >> n >> m;
for (int i = 1; i <= m; i++) {
f >> a >> b;
graf[a].push_back(b);
}
}
void tarjan(int nod) {
int l = graf[nod].size(), fiu, top;
index[nod] = lowlink[nod] = ++index_crt;
st.push(nod); in_stack[nod] = true;
for (int i = 0; i < l; i++) {
fiu = graf[nod][i];
if (!index[fiu]) tarjan(fiu);
if (in_stack[fiu]) lowlink[nod] = min(lowlink[nod], lowlink[fiu]);
}
if (lowlink[nod] >= index[nod]) {
nrcomp++;
do {
top = st.top();
st.pop();
in_stack[top] = false;
comp[top] = nrcomp;
} while (top != nod);
}
}
void scrie() {
g << nrcomp << '\n';
for (int i = 1; i <= nrcomp; i++, g << '\n')
for (int j = 1; j <= n; j++)
if (i == comp[j]) g << j << ' ';
}
int main() {
citeste();
for (int i = 1; i <= n; i++)
if (!index[i]) tarjan(i);
scrie();
}