Cod sursa(job #2702843)

Utilizator EckchartZgarcea Robert-Andrei Eckchart Data 6 februarie 2021 00:17:38
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 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 = 1e5;
int N, M;
vector<vector<int>> adj, transposed_adj;
vector<int> order;
bitset<MAX_NODE + 1> was_visited;
ifstream fin("ctc.in");
ofstream fout("ctc.out");


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

    for (const int adj_vertex : adj[vertex])
    {
        if (!was_visited[adj_vertex])
        {
            dfs1(adj_vertex);
        }
    }
    order.emplace_back(vertex);
}


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

    for (const int transposed_adj_vertex : transposed_adj[vertex])
    {
        if (!was_visited[transposed_adj_vertex])
        {
            dfs2(transposed_adj_vertex, cur_SCC);
        }
    }
}


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

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

    was_visited.reset();
    reverse(begin(order), end(order));
    for (const int vertex : order)
    {
        if (was_visited[vertex])
        {
            continue;
        }
        
        vector<int> cur_SCC;
        dfs2(vertex, cur_SCC);
        SCCs.emplace_back(cur_SCC);
    }

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


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

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

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

    Kosaraju();
}