Pagini recente » Cod sursa (job #502003) | Cod sursa (job #718387) | Cod sursa (job #2264441) | Cod sursa (job #2803089) | Cod sursa (job #3336587)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream f("ctc.in");
ofstream g("ctc.out");
vector<vector<int>> lista;
vector<vector<int>> lista_transpusa;
vector<int> viz;
stack<int> stiva;
vector<vector<int>> componente_conexe;
vector<int> componenta;
void DFS1(int x)
{
viz[x - 1] = 1;
for(int vecin : lista[x - 1])
if(viz[vecin - 1] == 0)
DFS1(vecin);
stiva.push(x);
}
void DFS2(int x)
{
viz[x - 1] = 1;
componenta.push_back(x);
for(int vecin : lista_transpusa[x - 1])
if(viz[vecin - 1] == 0)
DFS2(vecin);
}
int main()
{
int n, m, x, y;
f >> n >> m;
lista.resize(n);
lista_transpusa.resize(n);
for(int i = 0; i < m; i++)
{
f >> x >> y;
lista[x - 1].push_back(y);
lista_transpusa[y - 1].push_back(x);
}
// DFS pe graful normal
viz.assign(n, 0);
for(int i = 0; i < n; i++)
if(viz[i] == 0)
DFS1(i + 1);
// DFS pe graful transpus in ordinea din stiva
viz.assign(n, 0);
while(!stiva.empty())
{
int nod = stiva.top();
stiva.pop();
if(viz[nod - 1] == 0)
{
componenta.clear();
DFS2(nod);
componente_conexe.push_back(componenta);
}
}
cout << componente_conexe.size() << "\n";
for(vector<int> componenta : componente_conexe)
{
for(int nod : componenta)
cout << nod << " ";
cout << "\n";
}
return 0;
}