Cod sursa(job #2974328)

Utilizator IanisBelu Ianis Ianis Data 3 februarie 2023 21:01:21
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

#ifdef LOCAL
ifstream fin("input.txt");
#define fout cout
#else
#include <bits/stdc++.h>
ifstream fin("ctc.in");
ofstream fout("ctc.out");
#endif

const int NMAX = 1e5+5;

int n, m, s;
vector<int> g[NMAX];
vector<int> gt[NMAX];
stack<int> st;
bool viz[NMAX];
vector<vector<int>> ans;

void read() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
}

void dfs1(int x) {
    viz[x] = true;
    for (auto &it : g[x]) {
        if (!viz[it])
            dfs1(it);
    }
    st.push(x);
}

void dfs2(int x) {
    viz[x] = false;
    ans.back().push_back(x);
    for (auto &it : gt[x]) {
        if (viz[it])
            dfs2(it);
    }
}

int main() {
    read();
    for (int i = 1; i <= n; i++)
        if (!viz[i])
            dfs1(i);
    
    while (!st.empty()) {
        if (viz[st.top()]) {
            ans.push_back({});
            dfs2(st.top());
        }
        st.pop();
    }

    fout << ans.size() << endl;
    for (auto &v : ans) {
        for (auto &it : v)
            fout << it << ' ';
        fout << endl;
    }

    return 0;
}