Cod sursa(job #2886244)

Utilizator marateodorescu11Teodorescu Mara marateodorescu11 Data 7 aprilie 2022 14:48:10
Problema Componente tare conexe Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
const int N = 1e5;

vector <int> succesori[N+1], predecesori[N+1];
vector <int> ctc[N+1];
vector <int> s;
bitset <N+1> viz;
int n, nc;

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

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

int main()
{
    int 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);
    }
    fin.close();
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs(i);
        }
    }
    viz.reset();
    for (int i = (int)s.size() - 1; i >= 0; i--)
    {
        if (!viz[s[i]])
        {
            nc++;
            dfs_t(s[i]);
        }
    }
    fout << nc << '\n';
    for (int i = 1; i <= nc; i++)
    {
        for (auto x: ctc[i])//afisez varfurile din componenta i:
        {
            fout << x << " ";
        }
        fout << '\n';
    }
    fout.close();
    return 0;
}