Cod sursa(job #2739824)

Utilizator MateiAruxandeiMateiStefan MateiAruxandei Data 10 aprilie 2021 11:21:54
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h>

using namespace std;

const int INF = (1 << 30), NMAX(100005);
using VI  = vector<int>;
using VVI = vector<VI>;
using VB  = vector<bool>;

void BUNA(const string& task = "")
{
    if (!task.empty())
        freopen((task + ".in").c_str(), "r", stdin),
                freopen((task + ".out").c_str(), "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
}
void PA()
{
    exit(0);
}

VI G[NMAX], GT[NMAX], rez[NMAX];
VB viz(NMAX), viz2(NMAX);
int postOrdine[NMAX], nr, cnt;

void DFS(int nod)
{
    viz[nod] = 1;
    for(auto it: G[nod])
        if(!viz[it])
            DFS(it);
    postOrdine[++nr] = nod;
}

void DFST(int nod){
    viz2[nod] = 1;
    rez[cnt].push_back(nod);
    for(auto it: GT[nod])
        if(!viz2[it])
            DFST(it);
}

int main()
{
    BUNA("ctc");
    int n, m;
    cin >> n >> m;

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

        G[x].push_back(y);
        GT[y].push_back(x);
    }

    for(int i = 1; i <= n; ++i)
        if(!viz[i])
            DFS(i);
    for(int i = nr; i >= 1; --i)
        if(!viz2[postOrdine[i]])
        {
            ++cnt;
            DFST(postOrdine[i]);
        }

    cout << cnt << '\n';
    for(int i = 1; i <= cnt; ++i){
        sort(rez[i].begin(), rez[i].end());
        for(auto it: rez[i])
            cout << it << ' ';
        cout << '\n';
    }
    PA();
}