Cod sursa(job #2798133)

Utilizator RobertLitaLita Robert RobertLita Data 10 noiembrie 2021 22:32:52
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
#define nmax 100005
using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

int n,m;
vector<int> la[nmax];
vector<int> la_t[nmax];
vector<int> topo;
vector<int> ctc[nmax];
bool viz1[nmax], viz2[nmax];
int comp[nmax];

void dfs1(int nod)
{
    viz1[nod] = 1;
    for(auto i:la[nod])
    {
        if(viz1[i] == 0)
            dfs1(i);
    }
    topo.push_back(nod);
}

void dfs2(int nod, int nr_comp)
{
    viz2[nod] = 1;
    comp[nod] = nr_comp;
    ctc[nr_comp].push_back(nod);
    for(auto i:la_t[nod])
        if(viz2[i] == 0)
            dfs2(i, nr_comp);
}

int main()
{
    int x, y, nr_comp = 0;
    f >> n >> m ;
    for(int i = 1; i <= m; i++)
    {
        f >> x >> y;
        la[x].push_back(y);
        la_t[y].push_back(x);
    }
    for(int i = 1; i <= n; i++)
        if(viz1[i] == 0)
        {
            dfs1(i);
        }
    reverse(topo.begin(), topo.end());
    for(auto i:topo)
    {
        if(comp[i] == 0)
        {
            nr_comp++;
            dfs2(i, nr_comp);
        }
    }
    g << nr_comp << '\n';
    for(int i = 1; i <= nr_comp; i++)
    {
        for(auto j:ctc[i])
            g << j << ' ';
        g << '\n';
    }
    return 0;
}