Cod sursa(job #3212507)

Utilizator rapidu36Victor Manz rapidu36 Data 11 martie 2024 20:30:00
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>

using namespace std;

const int N = 1e5;

vector <int> s[N+1];
vector <int> p[N+1];
vector <int> s_top;
vector <int> ctc[N];
bitset <N+1> viz;

void dfs_1(int x)
{
    viz[x] = 1;
    for (auto y: s[x])
    {
        if (!viz[y])
        {
            dfs_1(y);
        }
    }
    s_top.push_back(x);
}

void dfs_2(int x, int n_c)
{
    ctc[n_c].push_back(x);
    viz[x] = 1;
    for (auto y: p[x])
    {
        if (!viz[y])
        {
            dfs_2(y, n_c);
        }
    }
}

int main()
{
    ifstream in("ctc.in");
    ofstream out("ctc.out");
    int n, m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        s[x].push_back(y);
        p[y].push_back(x);
    }
    viz.reset();
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs_1(i);
        }
    }
    viz.reset();
    reverse(s_top.begin(), s_top.end());
    int nr_ctc = 0;
    for (auto x: s_top)
    {
        if (!viz[x])
        {
            dfs_2(x, nr_ctc);
            nr_ctc++;
        }
    }
    out << nr_ctc << "\n";
    for (int i = 0; i < nr_ctc; i++)
    {
        for (auto x: ctc[i])
        {
            out << x << " ";
        }
        out << "\n";
    }
    in.close();
    out.close();
    return 0;
}