Pagini recente » Cod sursa (job #2318818) | Cod sursa (job #3217077) | Cod sursa (job #3200375) | Cod sursa (job #2074618) | Cod sursa (job #2028037)
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#define MAX 100005
using namespace std;
int n, m, x, y;
vector<int> l[MAX];
stack<int> s;
int index[MAX], lowlink[MAX], ind;
bool onStack[MAX];
vector<int> c;
vector<vector<int> > ctc;
void tarjan(int x) {
lowlink[x] = index[x] = ++ind;
s.push(x);
onStack[x] = 1;
for(int i = 0; i < l[x].size(); ++i)
if(!index[l[x][i]]) {
tarjan(l[x][i]);
lowlink[x] = min(lowlink[x], lowlink[l[x][i]]);
}
else if(onStack[l[x][i]])
lowlink[x] = min(lowlink[x], index[l[x][i]]);
if(lowlink[x] == index[x]) {
int node;
do {
node = s.top();
s.pop();
onStack[node] = 0;
c.push_back(node);
} while(node != x);
ctc.push_back(c);
c.clear();
}
}
int main() {
ifstream f("ctc.in");
ofstream g("ctc.out");
f >> n >> m;
for(int i = 0; i < m; ++i) {
f >> x >> y;
l[x].push_back(y);
}
for(int i = 1; i <= n; ++i)
if(!index[i])
tarjan(i);
g << ctc.size() << "\n";
for(int i = 0; i < ctc.size(); ++i) {
for(int j = 0; j < ctc[i].size(); ++j)
g << ctc[i][j] << " ";
g << "\n";
}
return 0;
}