Cod sursa(job #2531005)

Utilizator MarcGrecMarc Grec MarcGrec Data 25 ianuarie 2020 15:53:54
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#define MAX_N 100000

#include <fstream>
#include <vector>
using namespace std;

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

int n, m, ctc, v[MAX_N + 1], vt[MAX_N + 1];
vector<int> G[MAX_N + 1], Gt[MAX_N + 1], C[MAX_N + 1];

void Df(int nod);
void Dft(int nod);

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

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

        G[x].push_back(y);

        Gt[y].push_back(x);
    }

    for (int i = 1; i <= n; ++i)
    {
        if ((v[i] == vt[i]) && (v[i] != 0)) { continue; }

        ++ctc;

        Df(i);
        Dft(i);
    }

    fout << ctc << '\n';

    for (int i = 1; i <= ctc; ++i)
    {
        for (int nod : C[i])
        {
            fout << nod << ' ';
        }

        fout << '\n';
    }

    fin.close();
    fout.close();
    return 0;
}

void Df(int nod)
{
    v[nod] = ctc;
    for (int vecin : G[nod])
    {
        if (((v[vecin] == vt[vecin]) || (v[vecin] == ctc)) && (v[vecin] != 0)) { continue; }

        Df(vecin);
    }
}

void Dft(int nod)
{
    vt[nod] = ctc;

    if (v[nod] == vt[nod]) { C[ctc].push_back(nod); }
    for (int vecin : Gt[nod])
    {
        if ((v[vecin] != ctc) || (v[vecin] == vt[vecin])) { continue; }

        Dft(vecin);
    }
}