Cod sursa(job #2760079)

Utilizator andreiiorgulescuandrei iorgulescu andreiiorgulescu Data 22 iunie 2021 19:26:30
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,nrctc;
bool viz[100005];
vector<int>a[100005],b[100005],sol[100005];
vector<int>tps;
void citire()
{
    in >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x,y;
        in >> x >> y;
        a[x].push_back(y);
        b[y].push_back(x);
    }
}

void DFS(int p)
{
    viz[p] = true;
    for (int i = 0; i < a[p].size(); i++)
        if (viz[a[p][i]] == false)
            DFS(a[p][i]);
    tps.push_back(p);
}

void DFS2(int p)
{
    sol[nrctc + 1].push_back(p);
    viz[p] = true;
    for (int i = 0; i < b[p].size(); i++)
        if (viz[b[p][i]] == false)
            DFS2(b[p][i]);
}

int main()
{
    citire();
    for (int i = 1; i <= n; i++)
        if (viz[i] == false)
            DFS(i);
    reverse(tps.begin(),tps.end());
    for(int i = 0 ; i <= n; i ++)
        viz[i] = 0;
    for (int i = 0; i < tps.size(); i++)
        {
            if(viz[tps[i]] == 0)
            {
                DFS2(tps[i]);
                nrctc++;
            }
        }
    out << nrctc << '\n';
    for (int i = 1; i <= nrctc; i++)
        sort(sol[i].begin(),sol[i].end());
    for (int i = 1; i <= nrctc; i++)
    {
        for (int j = 0; j < sol[i].size(); j++)
            out << sol[i][j] << " ";
        out << '\n';
    }
    return 0;
}