Pagini recente » Cod sursa (job #2600585) | Cod sursa (job #2101518) | Cod sursa (job #1105619) | Cod sursa (job #1462732) | Cod sursa (job #1318531)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define nmax 50001
using namespace std;
ifstream fin ("ctc.in");
ofstream fout ("ctc.out");
vector<int> v[nmax], transpose[nmax], sol[nmax], components[nmax];
vector <int> topo;
bool seen[nmax];
int c, n, m;
void dfs(int x){
seen[x] = true;
for(int i=0; i<v[x].size(); i++)
if(!seen[v[x][i]])
dfs(v[x][i]);
topo.push_back(x);
}
void kosajaru(int x){
seen[x] = true;
components[c].push_back(x);
for(int i=0; i<transpose[x].size(); i++){
if(!seen[transpose[x][i]])
kosajaru(transpose[x][i]);
}
}
int main(){
int x, y, i;
fin >> n >> m;
for(int i=1; i<=m; i++){
fin >> x >> y;
v[x].push_back(y); // the adjency list
transpose[y].push_back(x); // the transpose adjency list
}
for(int i=1; i<=n; i++)
if(!seen[i]) dfs(i); // the first dfs on the original graph
for(int i=1; i<=n; i++) seen[i] = false;
for(i=n-1; i>=0; i--){
if(!seen[topo[i]]){
c++;
kosajaru(topo[i]);
}
}
fout << c << "\n";
for(int i=1; i<=c; i++){
for(int j=0; j<components[i].size(); j++)
fout << components[i][j] << " ";
fout << "\n";
}
return 0;
}