Cod sursa(job #2728005)

Utilizator filipinezulDumitrascu Filip Teodor filipinezul Data 22 martie 2021 18:18:35
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>

using namespace std;

const int N = 100001;

bitset <N> viz;
vector <int> a[N], a_t[N];
vector <int> ctc[N];
stack <int> stiva;
int n, nc;

void dfs(int x)
{
    viz[x] = 1;
    for (auto y: a[x])
    {
        if (!viz[y])
        {
            dfs(y);
        }
    }
    stiva.push(x);
}

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

int main()
{
    ifstream in("ctc.in");
    ofstream out("ctc.out");
    int m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        a[x].push_back(y);
        a_t[y].push_back(x);
    }
    in.close();
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs(i);
        }
    }
    viz.reset();
    while (!stiva.empty())
    {
        int x = stiva.top();
        stiva.pop();
        if (!viz[x])
        {
            nc++;
            dfs_t(x);
        }
    }
    out << nc << "\n";
    for (int i = 1; i <= nc; i++)
    {
        for (auto x: ctc[i])
        {
            out << x << " ";
        }
        out << "\n";
    }
    out.close();
    return 0;
}