Cod sursa(job #3214199)

Utilizator gianiferSpita Alexandru-Mihai gianifer Data 13 martie 2024 21:21:39
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
#define N_MAX 100005
using namespace std;

ifstream fin("ctc.in");

ofstream fout("ctc.out");

vector<int> l[N_MAX];
vector<int> sortare;
vector<int> sol[N_MAX];
vector<int> l1[N_MAX];
int n, m;
bool viz[N_MAX];
int k;
void dfs(int nod)
{
    viz[nod] = true;
    for (auto it : l[nod])
    {
        if (!viz[it])
            dfs(it);
    }
    sortare.push_back(nod);
}
void kosaraju(int nod)
{
    sol[k].push_back(nod);
    viz[nod] = true;
    for (auto it : l1[nod])
    {
        if (!viz[it])
            kosaraju(it);
    }
}
int main()
{
    fin >> n >> m;
    while (m--)
    {
        int x, y;
        fin >> x >> y;
        l[x].push_back(y);
        l1[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
            dfs(i);
    }
    int lng = sortare.size();
    memset(viz, 0, sizeof(viz));
    for (int i = 1; i <= lng; i++)
    {
        int a = sortare[lng - i];
        if (!viz[a])
        {
            k++;
            kosaraju(a);
        }
    }
    fout << k << '\n';
    for (int i = 1; i <= k; i++)
    {
        for (auto x : sol[i])
            fout << x << ' ';
        fout << '\n';
    }
}