Cod sursa(job #2951175)

Utilizator MariusAndrei16Pricope Marius MariusAndrei16 Data 5 decembrie 2022 16:51:04
Problema Componente tare conexe Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 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[100001];
vector <int> GrafT[100001];
vector <int> ConexComponents[100001];
stack <int> nodesDFS;
int nrCTC;

int haveBeenThere[100001];

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++)
    {
        int vecin = Graf[node][i];
        if(haveBeenThere[vecin] == 0)
        {
            DFS(vecin);
        }
    }
    nodesDFS.push(node);
}

void DFS_T(int node)
{
    haveBeenThere[node] = 2;

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

    ConexComponents[nrCTC].push_back(node);
    
}

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();

        if(haveBeenThere[topNode] == 1)
        {
            ++nrCTC;
            DFS_T(topNode);
        }        
        nodesDFS.pop();
    }

    out << nrCTC << '\n';

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

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