Cod sursa(job #2886295)

Utilizator roxana.tololoiTololoi Ilinca-Roxana roxana.tololoi Data 7 aprilie 2022 15:47:22
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <bitset>
 
using namespace std;
 
ifstream fin("ctc.in");
ofstream fout("ctc.out");
 
const int N = 1e5;
vector <int> suc[N+1], pred[N+1];
vector <int> ctc[N+1];
vector <int> s;
bitset <N+1> viz;
int nc;
 
void dfs(int x)
{
    viz[x] = 1;
    for(auto y: suc[x])
    {
        if(!viz[y])
            dfs(y);
    }
    s.push_back(x);
}
 
void dfs_t(int x)
{
    ctc[nc].push_back(x);
    viz[x] = 1;
    for(auto y: pred[x])
    {
        if(!viz[y])
            dfs_t(y);
    }
}
 
int main()
{
    int n, m, x, y;
    fin >> n >> m;
    for(int i = 0; i < m; i++)
    {
        fin >> x >> y;
        suc[x].push_back(y);
        pred[y].push_back(x);
    }
    for(int i = 1; i <= n; i++)
    {
        if(!viz[i])
            dfs(i);
    }
    viz.reset(); // resetare elem din viz la 0
 
    for(int i = (int)s.size()-1; i >= 0; i--)
    {
        if(!viz[s[i]])
        {
            nc++;
            dfs_t(s[i]);
        }
    }
 
    fout << nc << "\n";
    for(int i = 1; i <= nc; i++)
    {
        for(auto x: ctc[i])
        {
            fout << x << " ";
        }
        fout << "\n";
    }
    return 0;
}