Cod sursa(job #2980692)

Utilizator alexia._.fFlorete Alexia Maria alexia._.f Data 16 februarie 2023 18:57:31
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <algorithm>

using namespace std;

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

const int NMAX = 100000;
vector <int> succesori[NMAX + 1], predecesori[NMAX + 1];
vector <int> v;
vector < vector<int> > componente_tare_conexe;
bitset <NMAX + 1> vizitat;
int n, m;

void depth_first_search_1(int node_start)
{
    vizitat[node_start] = 1;

    for(auto next_node : succesori[node_start])
    {
        if(!vizitat[next_node])
        {
            depth_first_search_1(next_node);
        }
    }
    v.push_back(node_start);
}

void depth_first_search_2(int node_start)
{
    vizitat[node_start] = 1;
    componente_tare_conexe[componente_tare_conexe.size() - 1].push_back(node_start);
    for(auto next_node : predecesori[node_start])
    {
        if(!vizitat[next_node])
        {
            depth_first_search_2(next_node);
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        in >> x >> y;
        succesori[x].push_back(y);
        predecesori[y].push_back(x);
    }

    for(int i = 1; i <= n; i++)
    {
        if(!vizitat[i])
        {
            depth_first_search_1(i);
        }
    }

    reverse(v.begin(), v.end());
    vizitat.reset();

    for(auto node : v)
    {
        if(!vizitat[node])
        {
            vector <int> componente;
            componente_tare_conexe.push_back(componente);
            depth_first_search_2(node);
        }
    }

    out << componente_tare_conexe.size() << "\n";

    for(auto node : componente_tare_conexe)
    {
        for(auto i : node)
        {
            out << i << " ";
        }
        out << "\n";
    }

    in.close();
    out.close();
    return 0;
}