Cod sursa(job #2940098)

Utilizator tomaionutIDorando tomaionut Data 14 noiembrie 2022 20:41:25
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
/// Kosaraju 
#include <bits/stdc++.h>

using namespace std;

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

int n, m, st[100005], top, nrscc; /// scc - strongly connected components
vector <int> a[100005], t[100005], scc[100005]; ///t - graful transpus
bitset <100005> viz;

void Dfs(int x)
{
    viz[x] = 1;
    for (auto w : a[x])
        if (viz[w] == 0)
            Dfs(w);
    st[++top] = x;
}


/// viz[i] = 1 - nevizitat
/// viz[i] = 0 - vizitat
void Dfs2(int x)
{
    viz[x] = 0;
    for (auto w : t[x])
        if (viz[w] == 1)
            Dfs2(w);
    scc[nrscc].push_back(x);
}

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

    /// sortarea topologica
    for (i = 1; i <= n; i++)
        if (viz[i] == 0)
            Dfs(i);

    for (i = n; i >= 1; i--)
        if (viz[st[i]] == 1)
        {
            nrscc++;
            Dfs2(st[i]);
        }

    cout << nrscc << "\n";
    for (i = 1; i <= nrscc; i++)
    {
        for (auto j : scc[i])
            cout << j << " ";
        cout << "\n";
    }
}

int main()
{
    int t;
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    t = 1;
    while (t--)
        Test_Case();

    return 0;
}