Cod sursa(job #3291507)

Utilizator nistor_dora_valentinaNistor Dora Valentina nistor_dora_valentina Data 4 aprilie 2025 21:41:29
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#include <bits/stdc++.h>

using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n, m, i, j, nr, x, y;
vector <int> v[100005], vt[100005];
stack <int> st;
set <int> nrcomp[100005];
bool viz[100005];
void dfs(int nod)
{
    viz[nod]=1;
    for(auto i: v[nod])
        if(viz[i]==0)
           dfs(i);
    st.push(nod);
}
void dfs2(int nod)
{
    viz[nod]=1;
    nrcomp[nr].insert(nod);
    for(auto i: vt[nod])
        if(viz[i]==0)
          dfs2(i);
}
int main()
{
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y;
        v[x].push_back(y);
        vt[y].push_back(x);
    }
    for(i=1; i<=n; i++)
        if(viz[i]==0)
          dfs(i);
    for(i=1; i<=n; i++)
        viz[i]=0;
    while(!st.empty())
    {
        int x=st.top();
        st.pop();
        if(viz[x]==0)
        {
            nr++;
            dfs2(x);
        }
    }
    fout<<nr<<'\n';
    for(i=1; i<=nr; i++)
    {
        for(auto j: nrcomp[i])
        fout<<j<<" ";
        fout<<'\n';
    }

    return 0;
}