Pagini recente » Cod sursa (job #1527924) | Cod sursa (job #1557923) | Cod sursa (job #456578) | Cod sursa (job #1221670) | Cod sursa (job #2795432)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <cstring>
#define VMAX 100000
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int V, E, ctc;
bool vis[VMAX];
vector <int> adj[VMAX];
vector <int> trans[VMAX];
vector <int> comp[VMAX];
stack <int> st;
void DFS1(int u)
{
vis[u] = true;
for (auto w:adj[u])
if (!vis[w]) DFS1(w);
st.push(u);
}
void DFS2(int u)
{
comp[ctc].push_back(u + 1);
vis[u] = true;
for (auto w:trans[u])
if (!vis[w]) DFS2(w);
}
int main()
{
fin >> V >> E;
int x, y;
while (E--) {
fin >> x >> y;
x--;
y--;
adj[x].push_back(y);
trans[y].push_back(x);
}
for (int i = 0; i < V; ++i)
if (!vis[i]) DFS1(i);
memset(vis, 0, sizeof(vis));
int u;
while (!st.empty()) {
u = st.top();
if (!vis[u]) {
DFS2(u);
ctc++;
}
st.pop();
}
fout << ctc << '\n';
for (int i = 0; i < ctc; ++i) {
for (auto elem:comp[i]) fout << elem << " ";
fout << '\n';
}
fin.close();
fout.close();
return 0;
}