Cod sursa(job #3346505)

Utilizator victor_diaconu_1111Victor Diaconu victor_diaconu_1111 Data 14 martie 2026 07:52:59
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <vector>
using namespace std;
const int nmax=1000001;
int n, m, nrc;
vector<int> g[nmax], gt[nmax], ctc[nmax], post;
bool viz[nmax];
ifstream fin("ctc.in");
ofstream fout("ctc.out");
#define cin fin
#define cout fout
void citire()
{
    int x, y;
    cin>>n>>m;
    while (m--)
    {
        cin>>x>>y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
}
void dfs(int vf)
{
    viz[vf]=1;
    for (int x:g[vf])
        if (viz[x]==0) dfs(x);
    post.push_back(vf);
}
void dfsgt(int vf)
{
    viz[vf]=0;
    ctc[nrc].push_back(vf);
    for (int x:gt[vf])
        if (viz[x]==1)
        dfsgt(x);
}
void componente()
{
    int i;
    for (i=1; i<=n; ++i)
        if (viz[i]==0) dfs(i);
    for (i=post.size()-1; i>=0; --i)
        if (viz[post[i]]==1)
    {
        nrc++;
        dfsgt(post[i]);
    }
}
void afisare()
{
    cout<<nrc<<'\n';
    for (int i=1; i<=nrc; ++i)
    {
        for (int x:ctc[i])
            cout<<x<<' ';
        cout<<'\n';
    }
}
int main()
{
    citire();
    componente();
    afisare();
    return 0;
}