Cod sursa(job #2239065)

Utilizator MocalinnoMoca Andrei Catalin Mocalinno Data 8 septembrie 2018 21:00:56
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
vector<vector<int>> g;
vector<vector<int>> gtrans;
vector<vector<int>> ctc;
vector<bool> viz;
stack<int> st;
int n, m, cnt, x, y;
void dfs(int x)
{
    viz[x] = true;
    for (auto y: g[x])
        if (!viz[y])
            dfs(y);
    st.push(x);
}
void dfs_reverse(int x)
{
    viz[x] = true;
    ctc[cnt].push_back(x);
    for (auto y: gtrans[x])
        if (!viz[y])
            dfs_reverse(y);
}
void kosaraju()
{
    int nod;
    for (int i = 1; i <= n; ++i)
        viz[i] = false;
    while (!st.empty())
    {
        nod = st.top();
        st.pop();
        if (!viz[nod])
        {
            dfs_reverse(nod);
            ++cnt;
        }
    }
}
int main()
{
    fin >> n >> m;
    g = vector<vector<int>>(n + 1);
    gtrans = vector<vector<int>>(n + 1);
    ctc = vector<vector<int>>(n + 1);
    viz = vector<bool>(n + 1);
    for (int i = 1; i <= m; ++i)
    {
        fin >> x >> y;
        g[x].push_back(y);
        gtrans[y].push_back(x);
    }
    for (int i = 1; i <= n; ++i)
        if (!viz[i])
            dfs(i);
    kosaraju();
    fout << cnt << '\n';
    for (int i = 0; i < cnt; ++i, fout << '\n')
        for (auto nod: ctc[i])
            fout << nod << ' ';
    fin.close();
    fout.close();
    return 0;
}