Pagini recente » Cod sursa (job #533977) | Cod sursa (job #1994709) | Cod sursa (job #342741) | Cod sursa (job #664594) | Cod sursa (job #1377103)
#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];
stack <int> st;
vector <int> graf[NMAX];
vector < vector <int> > componente;
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++;
vector <int> componenta_curenta;
do {
top = st.top();
st.pop();
in_stack[top] = false;
componenta_curenta.push_back(top);
} while (top != nod);
componente.push_back(componenta_curenta);
}
}
void scrie() {
int a, b;
a = componente.size(); g << a << '\n';
for (int i = 0; i < a; i++) {
b = componente[i].size();
for (int j = 0; j < b; j++) g << componente[i][j] << ' ';
g << '\n';
}
}
int main() {
citeste();
for (int i = 1; i <= n; i++)
if (!index[i]) tarjan(i);
scrie();
}