Cod sursa(job #3225437)

Utilizator rapidu36Victor Manz rapidu36 Data 17 aprilie 2024 16:41:40
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>

using namespace std;

const int N = 100000;

vector <vector <int>> succ;
vector <vector <int>> pred;
vector <vector <int>> ctc;
vector <int> sort_top;
bitset <N+1> viz;

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

void dfs_t(int x, vector <int> &c)
{
    viz[x] = 1;
    c.push_back(x);
    for (auto y: pred[x])
    {
        if (!viz[y])
        {
            dfs_t(y, c);
        }
    }
}

int main()
{
    ifstream in("ctc.in");
    ofstream out("ctc.out");
    int n, m;
    in >> n >> m;
    succ.resize(n + 1);
    pred.resize(n + 1);
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        succ[x].push_back(y);
        pred[y].push_back(x);
    }
    viz.reset();
    for (int x = 1; x <= n; x++)
    {
        if (!viz[x])
        {
            dfs(x);
        }
    }
    reverse(sort_top.begin(), sort_top.end());
    viz.reset();
    for (auto x: sort_top)
    {
        if (!viz[x])
        {
            vector <int> aux;
            dfs_t(x, aux);
            ctc.push_back(aux);
        }
    }
    out << ctc.size() << "\n";
    for (auto c: ctc)
    {
        for (auto x: c)
        {
            out << x << " ";
        }
        out << "\n";
    }
    in.close();
    out.close();
    return 0;
}