Cod sursa(job #3286694)

Utilizator mateistefan11matei stefan mateistefan11 Data 14 martie 2025 15:43:01
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n,m, viz[200005], a[200005], k, nrc;
vector<int> G[100005];
vector<int> GT[100005];
void DFS(int x)
{
    viz[x] = 1;
    for(auto e : G[x])
        if(!viz[e]) DFS(e);
    a[++k] = x;
}
void SortTop()
{
    for(int i = 1; i <= n; i++)
        if(!viz[i]) DFS(i);
}
void DFST(int x)
{
    viz[x] = nrc;
    for(auto e : GT[x])
        if(!viz[e]) DFST(e);
}
void Kosaraju()
{
    SortTop();
    for(int i = 1; i <= n; i++)
        viz[i] = 0;
    for(int i = n; i >= 1; i--)
    {
        if(viz[a[i]] == 0)
        {
            nrc++;
            DFST(a[i]);
        }
    }
}
int main()
{
    ios_base::sync_with_stdio(0);
    fin.tie(0);
    fout.tie(0);
    int i,j;
    fin >> n >> m;
    while(m--)
    {
        fin >> i >> j;
        G[i].push_back(j);
        GT[j].push_back(i);
    }
    Kosaraju();
    fout << nrc << "\n";
    for(i = 1; i <= nrc; i++, fout << "\n")
        for(j = 1; j <= n; j++)
            if(viz[j] == i) fout << j << " ";
    return 0;
}