Pagini recente » Cod sursa (job #3160619) | Cod sursa (job #1812578) | Cod sursa (job #2474542) | Cod sursa (job #704587) | Cod sursa (job #2725185)
//Algoritmul Kosaraju-Sharir
#include <fstream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");
const int N = 100001;
int n;
int m;
int nc = 0;
vector<int> a[N];
vector<int> a_t[N];
stack<int> st;
bool viz[N];
bool viz_t[N];
vector<int> ctc[N];
void dfs(int x) {
viz[x] = true;
for (auto y : a[x]) {
if (!viz[y]) {
dfs(y);
}
}
st.push(x);
}
void dfs_t(int x) {
ctc[nc].push_back(x);
viz_t[x] = true;
for (auto y : a_t[x]) {
if (!viz_t[y]) {
dfs_t(y);
}
}
}
int main() {
in >> n >> m;
for (int i = 0; i < m; i++) {
int x;
int y;
in >> x >> y;
a[x].push_back(y);
a_t[y].push_back(x);
}
for (int i = 1; i <= n; i++) {
if (!viz[i]) {
dfs(i);
}
}
while (!st.empty()) {
int x = st.top();
st.pop();
if (!viz_t[x]) {
dfs_t(x);
nc++;
}
}
out << nc << "\n";
for (int i = 0; i < nc; i++) {
for (auto y : ctc[i]) {
out << y << " ";
}
out << "\n";
}
}