Cod sursa(job #2923789)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 19 septembrie 2022 10:30:33
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const string filename = "ctc";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");

const int maxN = 100005;
int n, m, depth[maxN], low_link[maxN];
vector <int> G[maxN], stiva, comp;
vector <vector <int>> ctc;
bool used[maxN]
;

void dfs(int nod, int d)
{
    used[nod] = 1;
    stiva.push_back(nod);
    depth[nod] = d;
    low_link[nod] = depth[nod];
    for(int vecin : G[nod])
    {
        if(!used[vecin])
            dfs(vecin, d + 1);
        low_link[nod] = min(low_link[nod], low_link[vecin]);
    }
    if(low_link[nod] == depth[nod])
    {
        comp.clear();
        while(stiva.back() != nod)
        {
            comp.push_back(stiva.back());
            stiva.pop_back();
        }
        stiva.pop_back();
        comp.push_back(nod);
        ctc.push_back(comp);
    }
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }
    dfs(1, 1);
    fout << ctc.size() << '\n';
    for(auto c : ctc)
    {
        for(int elem : c)
            fout << elem << ' ';
        fout << '\n';
    }
    return 0;
}