Cod sursa(job #3336590)

Utilizator SomethingAndrei Marian Something Data 24 ianuarie 2026 22:49:37
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

vector<vector<int>> lista;
vector<vector<int>> lista_transpusa;
vector<int> viz;
stack<int> stiva;

vector<vector<int>> componente_conexe;
vector<int> componenta;

void DFS1(int x)
{
    viz[x - 1] = 1;
    for(int vecin : lista[x - 1])
        if(viz[vecin - 1] == 0)
            DFS1(vecin);
    stiva.push(x);
}

void DFS2(int x)
{
    viz[x - 1] = 1;
    componenta.push_back(x);
    for(int vecin : lista_transpusa[x - 1])
        if(viz[vecin - 1] == 0)
            DFS2(vecin);
}

int main()
{
    int n, m, x, y;
    f >> n >> m;
    lista.resize(n);
    lista_transpusa.resize(n);
    for(int i = 0; i < m; i++)
    {
        f >> x >> y;
        lista[x - 1].push_back(y);
        lista_transpusa[y - 1].push_back(x);
    }

    // DFS pe graful normal
    viz.assign(n, 0);
    for(int i = 0; i < n; i++)
        if(viz[i] == 0)
            DFS1(i + 1);

    // DFS pe graful transpus in ordinea din stiva
    viz.assign(n, 0);
    while(!stiva.empty())
    {
        int nod = stiva.top();
        stiva.pop();
        if(viz[nod - 1] == 0)
        {
            componenta.clear();
            DFS2(nod);
            componente_conexe.push_back(componenta);
        }
    }

    g << componente_conexe.size() << "\n";
    for(vector<int> componenta : componente_conexe)
    {
        for(int nod : componenta)
            g << nod << " ";
        g << "\n";
    }

    return 0;
}