Cod sursa(job #2799493)

Utilizator andrei.eEnachescu Andrei andrei.e Data 13 noiembrie 2021 11:50:15
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <stack>
#include <vector>
#include <algorithm>
using namespace std;

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

int n, m, nr_ctc;
bool vizitat[100001];
vector <int> g[100001], gt[100001];
stack <int> s;

struct tip
{
    int indice, nod;
}ctc[100001];

void dfs_t (int nod, int nr_ctc)
{
    ctc[nod].indice = nr_ctc;

    for (int i = 0; i < gt[nod].size(); i++)
        if (!ctc[gt[nod][i]].indice)
            dfs_t(gt[nod][i], nr_ctc);
}

void dfs (int nod)
{
    vizitat[nod] = 1;

    for (int i = 0; i < g[nod].size(); i++)
        if (!vizitat[g[nod][i]])
            dfs(g[nod][i]);

    s.push(nod);
}

bool criteriu (tip x, tip y)
{
    return x.indice < y.indice || (x.indice == y.indice && x.nod < y.nod);
}

int main()
{
    in >> n >> m;

    for (int i = 1; i <= n; i++)
    {
        //ctc[i].indice = 0;
        ctc[i].nod = i;
    }

    for (int i = 1; i <= m; i++)
    {
        int x, y;
        in >> x >> y;

        g[x].push_back(y);
        gt[y].push_back(x);
    }

    for (int i = 1; i <= n; i++)
        if (!vizitat[i])
            dfs(i);

    while (!s.empty())
    {
        if (!ctc[s.top()].indice)
        {
            nr_ctc++;
            dfs_t(s.top(), nr_ctc);
        }
        s.pop();
    }

    sort (ctc + 1, ctc + n + 1, criteriu);

    out << nr_ctc;
    for (int i = 1; i <= n; i++)
    {
        if (ctc[i].indice != ctc[i - 1].indice)
            out << '\n';
        out << ctc[i].nod << ' ';
    }
    in.close();
    out.close();
    return 0;
}