Cod sursa(job #3277803)

Utilizator EricDimiericdc EricDimi Data 17 februarie 2025 13:51:12
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

const int MAX_N = 100'000;

vector<int> G[MAX_N + 1];
vector<int> GT[MAX_N + 1];
set<int> ctc[MAX_N + 1];

int postordine[MAX_N + 1];
bitset<MAX_N + 1> viz;
int n, m, x, y, nrc, nr;

void dfs(int nod)
{
    viz[nod] = 1;
    for (auto vecin : G[nod])
        if (!viz[vecin])
            dfs(vecin);
    postordine[++nr] = nod;
}

void dfsT(int nod)
{
    viz[nod] = 0;
    ctc[nrc].insert(nod);
    for (auto vecin : GT[nod])
        if (viz[vecin])
            dfsT(vecin);
}

void Read()
{
    f >> n >> m;
    while (m--)
    {
        f >> x >> y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
}

void Kosaraju_Sharir()
{
    for (int i = 1; i <= n; i++)
        if (!viz[i])
            dfs(i);
    for (int i = n; i > 0; i--)
        if (viz[postordine[i]])
        {
            nrc++;
            dfsT(postordine[i]);
        }
}

void Print()
{
    g << nrc << "\n";
    for (int i = 1; i <= nrc; i++)
    {
        for (auto nod : ctc[i])
            g << nod << " ";
        g << "\n";
    }
}

int main()
{
    Read();
    Kosaraju_Sharir();
    Print();

    f.close();
    g.close();
    return 0;
}