Cod sursa(job #3226779)

Utilizator stefan05Vasilache Stefan stefan05 Data 22 aprilie 2024 19:56:55
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <vector>

#define NMAX 100005

using namespace std;

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

int n, m;
vector<int> l[NMAX];
vector<int> lt[NMAX];
vector<int> postord;
vector<int> cc[NMAX]; int nr;
bool f[NMAX];
int i;

void dfs(int);
void dfst(int);

signed main()
{
    fin >>n>>m;
    for (i = 1; i <= m; ++i)
    {
        int x, y;
        fin >>x>>y;
        l[x].push_back(y);
        lt[y].push_back(x);
    }

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

    for (i = postord.size()-1; i >= 0; --i)
    {
        int vf = postord[i];
        if (f[vf])
        {
            nr++;
            dfst(vf);
        }
    }

    fout <<nr<<'\n';
    for (i = 1; i <= nr; ++i)
    {
        for (auto vf: cc[i])
            fout <<vf<<' ';
        fout <<'\n';
    }
    fout.close();
    return 0;
}

void dfst(int vf)
{
    f[vf] = 0;
    cc[nr].push_back(vf);
    for (auto vfnou: lt[vf])
        if (f[vfnou])
            dfst(vfnou);
}

void dfs(int vf)
{
    f[vf] = 1;
    for (auto vfnou: l[vf])
        if (!f[vfnou])
            dfs(vfnou);
    postord.push_back(vf);
}