Cod sursa(job #3005634)

Utilizator Razvan_GabrielRazvan Gabriel Razvan_Gabriel Data 17 martie 2023 09:51:39
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>

using namespace std;

const int NMAX = 1e5 + 1;

vector <int> succesori[NMAX], predecesori[NMAX];
bitset <NMAX> viz;
vector <int> v;
vector <vector <int> > ctc;

void dfs(int x)
{
    viz[x] = 1;
    for(auto y: succesori[x])
        if(!viz[y])
            dfs(y);
    v.push_back(x);
}

void dfs_t(int x)
{
    viz[x] = 1;
    ctc[ctc.size() - 1].push_back(x);
    for(auto y: predecesori[x])
        if(!viz[y])
            dfs_t(y);
}

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

    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        succesori[x].push_back(y);
        predecesori[y].push_back(x);
    }

    for(int i = 1; i <= n; i++)
        if(!viz[i])
            dfs(i);

    reverse(v.begin(), v.end());
    viz.reset();

    for(auto x: v)
    {
        if(!viz[x])
        {
            vector <int> cmp;
            ctc.push_back(cmp);
            dfs_t(x);
        }
    }

    fout << ctc.size() << "\n";
    for(auto c: ctc)
    {
        for(auto x: c)
            fout << x << " ";
        fout << "\n";
    }
    return 0;
}