Cod sursa(job #3000032)

Utilizator dorupopDoru Pop dorupop Data 11 martie 2023 20:53:17
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

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

const int DIM = 100001;

int n, m, x, y;
vector<int> d[DIM], t[DIM], sol[DIM];
int timpfinal[DIM];
int scc[DIM], sccCnt,k;
bool vis[DIM];

void dfs1(int node) {
    vis[node] = true;
    for (int i=0;i<d[node].size();i++){
         int   adjNode=d[node][i];
        if (!vis[adjNode])
            dfs1(adjNode);
    }

    timpfinal[++k]=node;
}

void dfs2(int node) {
    vis[node] = true;
    sol[sccCnt].push_back(node);
    for (auto adjNode : t[node])
        if (!vis[adjNode])
            dfs2(adjNode);
}

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

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

    sccCnt = 0;
    memset(vis, false, sizeof(vis));
    for (int i=n;i>=1;i--) {
        if (!vis[timpfinal[i]]) {
            sccCnt++;
            dfs2(timpfinal[i]);
        }
    }

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

    return 0;
}