Pagini recente » Cod sursa (job #2324079) | Cod sursa (job #1666880) | Cod sursa (job #781546) | Cod sursa (job #1331366) | Cod sursa (job #3212974)
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
const int NMAX = 100001;
vector <int> s_top;
vector <int> s[NMAX];
vector <int> p[NMAX];
vector <int> ctc[NMAX];
bool viz[NMAX];
void resetare(int n){
for(int i = 0; i <= n; i++){
viz[i] = false;
}
}
void dfs_1(int x){
viz[x] = true;
for(auto y: s[x]){
if(!viz[y]){
dfs_1(y);
}
}
s_top.push_back(x);
}
void dfs_2(int x, int nr_c){
viz[x] = true;
ctc[nr_c].push_back(x);
for(auto y: p[x]){
if(!viz[y]){
dfs_2(y, nr_c);
}
}
}
int main()
{
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n, m;
fin >> n >> m;
for(int i = 0; i < m; i++){
int x, y;
fin >> x >> y;
s[x].push_back(y);
p[y].push_back(x);
}
for(int i = 1; i <= n; i++){
if(!viz[i]){
dfs_1(i);
}
}
reverse(s_top.begin(), s_top.end());
resetare(n);
int nr_c = 1;
for(auto x: s_top){
if(!viz[x]){
dfs_2(x, nr_c);
nr_c++;
}
}
fout << nr_c - 1 << "\n";
for(int i = 1; i < nr_c; i++){
for(auto x: ctc[i]){
fout << x << " ";
}
fout << "\n";
}
fin.close();
fout.close();
return 0;
}