Cod sursa(job #2972324)

Utilizator raulboancaBoanca Raul Alin raulboanca Data 29 ianuarie 2023 10:30:41
Problema Componente tare conexe Scor 24
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("ctc.in");
ofstream g("ctc.out");
vector<int> v[50005];
vector<int> v_invers[50005];
int n,m;
int x,y;
int t[50005];
int timp;
int s;
bool viz[50005];
stack<int> st;
int componente[50005];
int numar_componente;
vector<int> comp[50005];

void citire()
{
    f >> n >> m;
    for (int i=1; i<=m; i++)
    {
        f >> x >> y;
        v[x].push_back(y);
        v_invers[y].push_back(x);
    }
}

void dfs(int nod)
{
    viz[nod] = true;
    for (auto k : v[nod])
    {
        if (!viz[k])
        {
            dfs(k);
        }
    }
    st.push(nod);
}

void dfs_invers(int nod)
{
    componente[nod] = numar_componente;
    comp[numar_componente].push_back(nod);
    for (auto k : v_invers[nod])
    {
        if (!componente[k])
        {
            dfs_invers(k);
        }
    }
}

void kosaraju()
{
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs(i);
        }
    }
    while (!st.empty())
    {
        int nod = st.top();
        st.pop();
        if (!componente[nod])
        {
            numar_componente++;
            dfs_invers(nod);
        }
    }
}

void afisare()
{
    g << numar_componente << endl;
    for (int i = 1; i <= numar_componente; i++)
    {
        g << "Componenta tare conexa " << i << ": ";
        for (auto k : comp[i])
        {
            g << k << " ";
        }
        g << endl;
    }
}

int main()
{
    citire();
    kosaraju();
    afisare();
    return 0;
}