Pagini recente » Cod sursa (job #3353977) | Cod sursa (job #808484) | Cod sursa (job #3353980) | Borderou de evaluare (job #1501380) | Cod sursa (job #3353974)
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void dfs_s(int x, vector <bool> &viz, vector <vector <int>> &l_s, stack <int> &s) {
viz[x] = true;
for (auto y: l_s[x]) {
if (!viz[y]) {
dfs_s(y, viz, l_s, s);
}
}
s.push(x);
}
void dfs_p(int x, vector <bool> &viz, vector <vector <int>> &l_p, vector <int> &ctc) {
viz[x] = true;
ctc.push_back(x);
for (auto y: l_p[x]) {
if (!viz[y]) {
dfs_p(y, viz, l_p, ctc);
}
}
}
int main() {
ifstream in("ctc.in");
ofstream out("ctc.out");
int n, m;
in >> n >> m;
vector <vector <int>> l_s(n + 1);
vector <vector <int>> l_p(n + 1);
for (int i = 0; i < m; i++) {
int x, y;
in >> x >> y;
l_s[x].push_back(y);
l_p[y].push_back(x); // pentru graful transpus
}
in.close();
// prima etapa: pseudosortarea topologica
stack <int> s;
vector <bool> viz(n + 1, false);
for (int i = 1; i <= n; i++) {
if (!viz[i]) {
dfs_s(i, viz, l_s, s);
}
}
// a doua etapa: obtinerea ctc pe baza stivei
vector <vector <int>> ctc;
fill(viz.begin(), viz.end(), false);
while (!s.empty()) {
int x = s.top();
s.pop();
if (!viz[x]) {
vector <int> ctc_c;
dfs_p(x, viz, l_p, ctc_c);
ctc.push_back(ctc_c);
}
}
out << ctc.size() << "\n";
for (auto c: ctc) {
for (auto x: c) {
out << x << " ";
}
out << "\n";
}
out.close();
return 0;
}