Cod sursa(job #3213257)

Utilizator Razvan_GabrielRazvan Gabriel Razvan_Gabriel Data 12 martie 2024 20:05:44
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 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];
vector <vector <int> > ctc;
bitset <NMAX + 1> viz;
vector <int> v;

void dfs(int x)
{
    viz[x] = true;

    for(auto y: succesori[x])
        if(!viz[y])
            dfs(y);

    v.push_back(x);
}

void dfs_t(int x)
{
    viz[x] = true;
    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 = 0; 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);

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

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

    fout << ctc.size() << "\n";

    for(auto x: ctc)
    {
        for(auto y: x)
            fout << y << " ";
        fout << "\n";
    }

    return 0;
}