Cod sursa(job #2951172)

Utilizator MariusAndrei16Pricope Marius MariusAndrei16 Data 5 decembrie 2022 16:45:17
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>


using namespace std;

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

int n, m;
vector <int> Graf[100000];
vector <int> GrafT[100000];
vector <int> ConexComponents[100000];
stack <int> nodesDFS;
int nrCTC;

int haveBeenThere[100000];

void Read()
{
    in >> n >> m;
    int x, y;
    for (int i = 0; i < m; i++)
    {
        in >> x >> y;
        Graf[x].push_back(y);
        GrafT[y].push_back(x);
    }
}

void DFS(int node)
{
    haveBeenThere[node] = 1;
    for (unsigned int i = 0; i < Graf[node].size(); i++)
    {
        if(haveBeenThere[Graf[node][i]] == 0)
        {
            int vecin = Graf[node][i];
            DFS(vecin);
        }
    }
    nodesDFS.push(node);
}

void DFS_T(int node)
{
    haveBeenThere[node] = 2;
    ConexComponents[nrCTC].push_back(node);

    for (int i = 0; i < GrafT[node].size(); i++)
    {
        if(haveBeenThere[GrafT[node][i]] == 1)
        {
            DFS_T(GrafT[node][i]);
        }
    }
    
}

void Solve()
{
    for (int i = 1; i <= n; i++)
    {
        if(haveBeenThere[i] == 0)
            DFS(i);
    }

    while (!nodesDFS.empty())
    {
        //cout << nodesDFS.top() << ' ';

        int topNode = nodesDFS.top();
        
        for (int i = 0; i < GrafT[topNode].size(); i++)
        {
            if(haveBeenThere[GrafT[topNode][i]] == 1)
            {
                ++nrCTC;
                DFS_T(GrafT[topNode][i]);
            }
        }
        
        nodesDFS.pop();
    }

    out << nrCTC << '\n';

    for (int i = 1; i <= nrCTC; i++)
    {
        for (int j = ConexComponents[i].size() - 1 ; j >= 0; j--)
        {
            out << ConexComponents[i][j] << ' ';
        }
        out << endl;
    }
}

int main()
{
    Read();
    Solve();
    return 0;
}