Cod sursa(job #2702930)

Utilizator EckchartZgarcea Robert-Andrei Eckchart Data 6 februarie 2021 12:23:12
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <bits/stdc++.h>
#include <cassert>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pi = pair<int, int>;
using pl = pair<ll, ll>;
using pd = pair<double, double>;
using pld = pair<ld, ld>;
const int MAX_NODE_IDX = 1e5;
vector<vector<int>> adj, trans_adj;
stack<int> top_order;
bitset<MAX_NODE_IDX + 1> was_visited;
ifstream fin("ctc.in");
ofstream fout("ctc.out");


void dfs1(const int vertex)
{
    was_visited[vertex] = 1;

    for (const int adj_node : adj[vertex])
    {
        if (!was_visited[adj_node])
        {
            dfs1(adj_node);
        }
    }
    top_order.emplace(vertex);
}


void dfs2(const int vertex, vector<int> &SCC)
{
    was_visited[vertex] = 1;
    SCC.emplace_back(vertex);

    for (const int adj_node : trans_adj[vertex])
    {
        if (!was_visited[adj_node])
        {
            dfs2(adj_node, SCC);
        }
    }
}


void Kosaraju(const int nr_nodes)
{
    vector<vector<int>> SCCs;
    SCCs.reserve(nr_nodes);

    for (int node = 1; node <= nr_nodes; ++node)
    {
        if (!was_visited[node])
        {
            dfs1(node);
        }
    }

    was_visited.reset();
    while (!top_order.empty())
    {
        if (!was_visited[top_order.top()])
        {
            vector<int> SCC;
            dfs2(top_order.top(), SCC);
            SCCs.emplace_back(SCC);
        }
        top_order.pop();
    }

    fout << SCCs.size() << "\n";
    for (const auto &SCC : SCCs)
    {
        for (const int SCC_vertex : SCC)
        {
            fout << SCC_vertex << " ";
        }
        fout << "\n";
    }
}


int main()
{
    int N, M;
    fin >> N >> M;

    adj.reserve(N + 1), trans_adj.reserve(M + 1);
    while (M--)
    {
        int x, y;
        fin >> x >> y;

        adj[x].emplace_back(y);
        trans_adj[y].emplace_back(x);
    }

    Kosaraju(N);
}