Pagini recente » Cod sursa (job #2859690) | Cod sursa (job #3032858) | Cod sursa (job #2398515) | Cod sursa (job #2940033) | Cod sursa (job #2929465)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define int long long
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int rez;
vector <vector <int>> rezz;
void ctc(int aici, vector <vector <int>> & adjL, vector <pair <int, int>> & viz, stack <int> & stv, int pozStiva, vector <int> & inStiva){
for (auto &it : adjL[aici]){
if (viz[it].first == 0){
viz[it].first = 1;
viz[it].second = pozStiva;
inStiva[it] = 1;
stv.push(it);
ctc(it, adjL, viz, stv, pozStiva + 1, inStiva);
/// fout << "Sunt in if; Am schimbat viz-ul din " << aici << ", facand minimul dintre " << viz[aici].second << " si " << viz[it].second << "\n";
viz[aici].second = min(viz[aici].second, viz[it].second);
}
else if (inStiva[it]){
/// fout << "Sunt in else; Am schimbat viz-ul din " << aici << ", facand minimul dintre " << viz[aici].second << " si " << viz[it].second << "\n";
viz[aici].second = min(viz[aici].second, viz[it].second);
}
}
viz[aici].first = 2;
if (viz[aici].second == pozStiva-1){
rezz.push_back({});
while (aici != stv.top()){
rezz[rez].push_back(stv.top()+1);
inStiva[stv.top()] = 0;
stv.pop();
}
rezz[rez].push_back(aici+1);
inStiva[aici] = 0;
stv.pop();
++rez;
}
}
int n, m, nr1, nr2;
int32_t main()
{
fin >> n >> m;
vector <vector <int>> adjL(n);
vector <int> inStiva(n);
for (int i = 0; i < m; ++i)
{
fin >> nr1 >> nr2;
adjL[nr1-1].push_back(nr2-1);
}
vector <pair <int, int>> viz(n); ///am aici si stadiul (0 neviz, 1 viz incomplet, 2 viz complet), si nodul minim catre care arata
stack <int> stv;
for (int i = 0; i < n; ++i){
if (viz[i].first == 0){
viz[i].first = 1;
viz[i].second = 0;
inStiva[i] = 1;
stv.push(i);
ctc(i, adjL, viz, stv, 1, inStiva); /// Foarte important: viz.second trebuie sa tina pozitia in stiva, nu numarul nodului in sine
}
}
fout << rez << '\n';
for (int i = 0; i < rez; ++i){
for (auto j : rezz[i])
fout << j << ' ';
fout << '\n';
}
cout << stv.size();
return 0;
}