Cod sursa(job #3128800)

Utilizator hurjui12AlexandruHurjui Alexandru-Mihai hurjui12Alexandru Data 10 mai 2023 22:28:49
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>
using namespace std;
using llx = long long;

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

vector <vector <int>> v, vt;
vector <bool> viz;
vector <int> noduri_iesite;
vector <vector <int>> comp;

void dfs1(int x)
{
    viz[x] = 1;

    for (const auto &nv : v[x])
        if (viz[nv] == 0)
            dfs1(nv);

    noduri_iesite.push_back(x);
}

void dfs2(int x)
{
    viz[x] = 1;
    comp.end()[-1].push_back(x);

    for (const auto &nv : vt[x])
        if (viz[nv] == 0)
            dfs2(nv);
}

int main()
{
    int n, m, i, x, y;

    fin >> n >> m;
    v.resize(n+1);
    vt.resize(n+1);

    for (i = 1; i<=m; i++)
    {
        fin >> x >> y;
        v[x].push_back(y);
        vt[y].push_back(x);
    }

    viz.assign(n+1, 0);
    for (i = 1; i<=n; i++)
        if (viz[i] == 0)
            dfs1(i);
    
    reverse(noduri_iesite.begin(), noduri_iesite.end());
    viz.assign(n+1, 0);
    for (const auto &nod : noduri_iesite)
        if (viz[nod] == 0)
        {
            comp.push_back(vector <int>());
            dfs2(nod);
        }

    fout << comp.size() << '\n';
    for (const auto &componenta : comp)
    {
        for (const auto &nod : componenta)
            fout << nod << ' ';
        fout << '\n';
    }
    return 0;
}