Cod sursa(job #3344409)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 1 martie 2026 22:43:05
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
using namespace std;

const int MAX = 100005;
vector<int> scc, graph[MAX], rgraph[MAX];
vector<vector<int>> ans;
int visited[MAX], topSort[MAX], k;

void dfs(int node)
{
    visited[node] = 1;
    for (int next : graph[node])
        if (!visited[next])
            dfs(next);

    topSort[++k] = node;
}

void kosaraju(int node)
{
    visited[node] = 1;
    scc.push_back(node);
    for (int next : rgraph[node])
        if (!visited[next])
            kosaraju(next);
}

int main()
{
    ifstream fin("ctc.in");
    ofstream fout("ctc.out");
    int n, m;
    fin >> n >> m;

    for (int i = 1; i <= m; ++i)
    {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
        rgraph[y].push_back(x);
    }

    for (int i = 1; i <= n; ++i)
        if (!visited[i])
            dfs(i);

    for (int i = 1; i <= n; ++i)
        visited[i] = 0;

    for (int i = k; i >= 1; --i)
    {
        int next = topSort[i];
        if (!visited[next])
        {
            scc.clear();
            kosaraju(next);
            ans.push_back(scc);
        }
    }

    fout << ans.size() << "\n";
    for (vector<int> cmp : ans)
    {
        for (int node : cmp)
            fout << node << " ";
        fout << "\n";
    }

    return 0;
}