Cod sursa(job #2725191)

Utilizator nicoleta_mnMartin nicoleta nicoleta_mn Data 18 martie 2021 15:31:06
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream in("ctc.in");
ofstream out("ctc.out");

int const N = 100001;

int n, m;
stack <int> st;
vector <int> a[N], a_t[N], ctc[N];
int nc;
bool viz[N], viz_t[N];

void dfs(int x)
{
    viz[x] = 1;
    for(auto y:a[x])
    {
        if(!viz[y])
            dfs(y);
    }
    st.push(x);
}

void dfs_t(int x)
{
    ctc[nc].push_back(x);
    viz_t[x] = 1;
    for(auto y:a_t[x])
    {
        if(!viz_t[y])
            dfs_t(y);
    }
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        in >> x >> y;
        a[x].push_back(y);
        a_t[y].push_back(x);
    }
    for(int i = 1; i <= n; i++)
    {
        if(!viz[i])
        {
            dfs(i);
        }
    }
    while(!st.empty())
    { int x=st.top();
        if(viz_t[x] == 0)
        {
            dfs_t(x);
            nc++;
        }
        st.pop();
    }
    out<<nc<<'\n';
    for(int i=0;i<nc; i++)
    {
        for(auto j:ctc[i])
        {
            out<<j<<" ";
        }
        out<<'\n';
    }
    return 0;
}