Pagini recente » Cod sursa (job #3177635) | Cod sursa (job #924143) | Cod sursa (job #2192958) | Cod sursa (job #3257127) | Cod sursa (job #1895832)
#include <bits/stdc++.h>
using namespace std;
const int N_MAX = 1e5 + 5;
int n, m, strongComponents;
vector <int> g[N_MAX], t[N_MAX], solution[N_MAX];
bitset <N_MAX> visited;
stack <int> st;
void read() {
ifstream fin("ctc.in");
fin >> n >> m;
while (m--) {
int x, y;
fin >> x >> y;
g[x].emplace_back(y);
t[y].emplace_back(x);
}
fin.close();
}
void dfs_g(int node) {
visited.set(node);
for (const auto &son : g[node]) {
if (!visited[son]) {
dfs_g(son);
}
}
st.emplace(node);
}
void dfs_t(int node) {
visited.reset(node);
solution[strongComponents].emplace_back(node);
for (const auto &son : t[node]) {
if (visited[son]) {
dfs_t(son);
}
}
}
void solve() {
for (int node = 1; node <= n; ++node) {
if (!visited[node]) {
dfs_g(node);
}
}
while (!st.empty()) {
int node = st.top();
if (visited[node]) {
++strongComponents;
dfs_t(node);
}
st.pop();
}
}
void write() {
ofstream fout("ctc.out");
fout << strongComponents << '\n';
for (int i = 1; i <= strongComponents; ++i) {
for (const auto &node : solution[i]) {
fout << node << ' ';
}
fout << '\n';
}
fout.close();
}
int main() {
read();
solve();
write();
return 0;
}