Cod sursa(job #2971499)

Utilizator rapidu36Victor Manz rapidu36 Data 27 ianuarie 2023 14:59:21
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>

using namespace std;

const int N = 1e5;

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

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

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

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;
        succesori[x].push_back(y);
        predecesori[y].push_back(x);
    }
    ///construim cu dfs-uri ale grafului initial vectorul v corspunzator unei
    ///sortari topologice a metagrafului ctc-urilor
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs(i);
        }
    }
    reverse(v.begin(), v.end());
    viz.reset();
    for (auto x: v)
    {
        if (!viz[x])
        {
            vector <int> comp;
            ctc.push_back(comp);
            dfs_t(x);
        }
    }
    out << ctc.size() << "\n";
    for (auto c: ctc)
    {
        for (auto x: c)
        {
            out << x << " ";
        }
        out << "\n";
    }
    in.close();
    out.close();
    return 0;
}