Pagini recente » Cod sursa (job #2878461) | Cod sursa (job #2203137) | Cod sursa (job #3042184) | Cod sursa (job #387732) | Cod sursa (job #1697754)
#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;
vector <int> graf[NMAX];
int ind_crt;
int ind[NMAX];
int lowlink[NMAX];
bool in_stack[NMAX];
stack <int> stiva;
vector < vector <int> > componente;
void citeste() {
f >> n >> m;
int a, b;
for (int i = 1; i <= m; i++) {
f >> a >> b;
graf[a].push_back(b);
}
}
void DFS(int nod) {
if (ind[nod]) return;
ind_crt++;
ind[nod] = lowlink[nod] = ind_crt;
in_stack[nod] = true;
stiva.push(nod);
int l, fiu;
l = graf[nod].size();
for (int i = 0; i < l; i++) {
fiu = graf[nod][i];
DFS(fiu);
if (!in_stack[fiu]) continue;
lowlink[nod] = min(lowlink[fiu], ind[nod]);
}
if (lowlink[nod] != ind[nod]) return;
vector <int> componenta_curenta;
int top;
do {
top = stiva.top();
stiva.pop();
in_stack[top] = false;
componenta_curenta.push_back(top);
} while (top != nod);
componente.push_back(componenta_curenta);
}
void scrie() {
int l1, l2;
l1 = componente.size();
g <<l1 << '\n';
for (int i = 0; i < l1; i++) {
l2 = componente[i].size();
for (int j = 0; j < l2; j++) g <<componente[i][j] << ' ';
g <<'\n';
}
}
void rezolva() {
for (int i = 1; i <= n; i++)
if (!ind[i]) DFS(i);
}
int main() {
citeste();
rezolva();
scrie();
return 0;
}