Cod sursa(job #3241720)

Utilizator bogdan1479Luca Bogdan Alexandru bogdan1479 Data 3 septembrie 2024 09:33:03
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <vector>

using namespace std;

const int NMAX = 1e5;

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

int n, m, nrc;
vector<int> G[NMAX + 1], GT[NMAX + 1], CTC[NMAX + 1], Post;
bool viz[NMAX + 1];

void citire()
{
    int x, y;
    fin >> n >> m;
    while(m--)
    {
        fin >> x >> y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
}

void dfs(int i)
{
    viz[i] = 1;
    for(auto x : G[i])
        if(!viz[x])
            dfs(x);
    Post.push_back(i);
}

void dfsGT(int i)
{
    viz[i] = 0;
    CTC[nrc].push_back(i);
    for(auto x : GT[i])
        if(viz[x])
            dfsGT(x);
}

void componente()
{
    for(int i = 1; i <= n; ++i)
        if(!viz[i])
            dfs(i);
    for(auto it = Post.crbegin(); it != Post.crend(); ++it)
        if(viz[*it])
        {
            ++nrc;
            dfsGT(*it);
        }
}

void afisare()
{
    fout << nrc << '\n';
    for(int i = 1; i <= nrc; ++i)
    {
        for(auto x : CTC[i])
            fout << x << ' ';
        fout << '\n';
    }
}

int main()
{
    citire();
    componente();
    afisare();
    return 0;
}