Cod sursa(job #2530741)

Utilizator AndreiJJIordan Andrei AndreiJJ Data 25 ianuarie 2020 11:21:12
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>

using namespace std;

const int N = 1e5 + 5;

vector <int> L[N], T[N], scc[N];
bitset <N> seen;
stack <int> st;
int nodes, edges, nr_scc;

void Read ()
{
    ifstream fin ("ctc.in");
    int x, y;
    fin >> nodes >> edges;
    for (int i = 1; i <= edges; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
        T[y].push_back(x);
    }
}

void First_DFS (int k)
{
    seen[k] = 1;
    for (auto j : L[k])
        if (!seen[j])
            First_DFS(j);
    st.push(k);
}

void Second_DFS (int k)
{
    seen[k] = 0;
    for (auto j : T[k])
        if (seen[j])
            Second_DFS(j);
    scc[nr_scc].push_back(k);
}

void Kosaraju ()
{
    int i;
    for (i = 1; i <= nodes; i++)
        if (!seen[i])
            First_DFS(i);
    while (!st.empty())
    {
        int k = st.top();
        st.pop();
        if (seen[k])
        {
            nr_scc++;
            Second_DFS(k);
        }
    }
    ofstream fout ("ctc.out");
    fout << nr_scc << "\n";
    for (i = 1; i <= nr_scc; i++)
    {
        for (auto j : scc[i])
            fout << j << " ";
        fout << "\n";
    }
}

int main()
{
    Read();
    Kosaraju();
    return 0;
}