Cod sursa(job #3215621)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 15 martie 2024 10:57:31
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

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

const int DIM = 100010;

int n, m;
vector<int> l[DIM], t[DIM], nodes, scc[DIM];
bool visited[DIM];

void dfs1(int node) {
    visited[node] = true;
    for (auto adjNode : l[node])
        if (!visited[adjNode])
            dfs1(adjNode);
    nodes.push_back(node);
}

void dfs2(int node, int ind) {
    visited[node] = true;
    scc[ind].push_back(node);
    for (auto adjNode : t[node])
        if (!visited[adjNode])
            dfs2(adjNode, ind);
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;
        l[x].push_back(y);
        t[y].push_back(x);
    }

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

    memset(visited, false, sizeof(visited));
    int sccCount = 0;
    for (auto it = nodes.rbegin(); it != nodes.rend(); it++) {
        int node = *it;
        if (!visited[node])
            dfs2(node, ++sccCount);
    }

    fout << sccCount << '\n';
    for (int i = 1; i <= sccCount; i++) {
        for (auto node : scc[i])
            fout << node << ' ';
        fout << '\n';
    }

    return 0;
}