Cod sursa(job #2663116)

Utilizator Silviu.Stancioiu@gmail.comSilviu Stancioiu [email protected] Data 25 octombrie 2020 13:36:58
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <vector>

constexpr auto max_n = 100005;

using namespace std;

vector<int> graph[max_n];
vector<int> transposed_graph[max_n];
bool visited[max_n] = { 0 };
int node_order[max_n];
int node_order_count = 0;
vector<int> components[max_n];
int componentCount = 0;

void dfs1(const int node)
{
    if (visited[node])
        return;

    visited[node] = true;
    for (auto neighbor : graph[node])
        dfs1(neighbor);

    node_order[node_order_count++] = node;
}

void dfs2(const int node)
{
    if (visited[node])
        return;

    visited[node] = true;

    components[componentCount].push_back(node);
    
    for (auto neighbor : transposed_graph[node])
        dfs2(neighbor);
}

int main()
{
    ifstream fin("ctc.in");
    ofstream fout("ctc.out");

    int n, m;
    fin >> n >> m;

    for (auto i = 0; i < m; i++)
    {
        int x, y;
        fin >> x >> y;
        x--;
        y--;

        graph[x].push_back(y);
        transposed_graph[y].push_back(x);
    }

    fin.close();

    for (auto i = 0; i < n; i++)
        if (!visited[i])
            dfs1(i);

    for (auto&& i : visited)
        i = false;

    auto num_components = 0;
    
    for (auto i = node_order_count - 1; i >= 0; i--)
    {
        const auto node = node_order[i];

        if (!visited[node])
            dfs2(node);

        componentCount++;

        if (!components[componentCount - 1].empty())
            num_components++;
    }

    fout << num_components << endl;
    for (auto& component : components)
    {
        if (!component.empty())
        {
            for (auto node : component)
                fout << node + 1 << " ";
            fout << endl;
        }
    }

    fout.close();
    return 0;
}