Pagini recente » Cod sursa (job #2869552) | Cod sursa (job #2513360) | Cod sursa (job #17261) | Istoria paginii runda/pt_round14 | Cod sursa (job #2962083)
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
#include <fstream>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
const int nmax = 1e5 + 1;
vector <int> g[nmax], gt[nmax], compConexe[nmax];
stack <int> st;
int viz[nmax], nrComp;
void DFS1(int nod)
{
viz[nod] = 1;
for (auto i : g[nod])
if (viz[i] == 0)
DFS1(i);
st.push(nod);
}
void DFS2(int nod)
{
viz[nod] = 2;
compConexe[nrComp].push_back(nod);
for (auto i : gt[nod])
if (viz[i] == 1)
DFS2(i);
}
int main()
{
int n, m;
int x, y;
fin >> n >> m;
for (int i = 1; i <= m; ++i) {
fin >> x >> y;
g[x].push_back(y);
gt[y].push_back(x);
}
for (int i = 1; i <= n; ++i) // dfs pe graful normal din fiecare nod
if (viz[i] == 0)
DFS1(i);
while (!st.empty()) { // parcurgem stiva in ordine inversa si facem dfs pe gradul transpus
int nod = st.top();
if (viz[nod] == 1) {
++nrComp;
DFS2(nod);
}
st.pop();
}
fout << nrComp << "\n";
for (int i = 1; i <= nrComp; ++i) {
for (int aux : compConexe[i])
fout << aux << " ";
fout << "\n";
}
return 0;
}