Cod sursa(job #2886282)

Utilizator TeoRoGaming_YgVoinea Ionut-Florin TeoRoGaming_Yg Data 7 aprilie 2022 15:30:16
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 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;
}