Cod sursa(job #2945910)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 24 noiembrie 2022 12:29:18
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream cin("ctc.in");
ofstream cout("ctc.out");


int n,m,ctc,idx;
vector<int> c,level,low;
vector<vector<int> > sirad,cc;
stack<int> st;
vector<bool> instk,viz;

void Tarjan();
void Dfs();

int main()
{
    int a,b;
    cin>>n>>m;
    sirad = vector<vector<int>>(n+1);
    viz = instk = vector<bool>(n+1);
    level = low = vector<int>(n+1);
    for(int i=1;i<=m;++i)
    {
        cin>>a>>b;
        sirad[a].push_back(b);
    }
    Tarjan();
    return 0;
}
void Dfs(int x)
{
    st.push(x);
    instk[x] = 1;
    viz[x] = 1;
    level[x] = low[x] = ++idx;

    for(auto i : sirad[x])
        if(!viz[i])
        {
            Dfs(i);
            low[x] = min(low[x],low[i]);
        }
        else if(instk[i])low[x] = min(low[x],level[i]);

    if(level[x] == low[x])
    {
        c.clear();
        while(!st.empty())
        {
            int a = st.top();
            st.pop();
            instk[a] = 0;
            c.push_back(a);
            if(level[a]==low[a])break;
        }
        cc.push_back(c);
    }

}

void Tarjan()
{

    for(int i=1;i<=n;++i)
    {
        if(!viz[i])
        {
            Dfs(i);
        }
    }
    cout<<cc.size()<<'\n';
    for(auto i : cc)
    {
        for(auto j:i)cout<<j<<' ';
        cout<<'\n';
    }
}